amg182 Posted August 27, 2011 Share Posted August 27, 2011 Hi i am trying to echo out my results in alphabetical order but have little knowledge working with arrays and usort function. I tried the following but only echoes results in no particular order. can someone advise: $result = mysql_query("SELECT * FROM cars"); while($row = mysql_fetch_array($result)) { $sort[] = $row['Model']; } usort($sort); print_r ($sort); ?> Please go easy on me, if i am doing something totaly wrong...still trying to get my head around this language... Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 28, 2011 Share Posted August 28, 2011 Don't use PHP to sort the records, use the MySQL ORDER BY to sort the options. Also, don't use '*' to get all the fields if you only need model $query = "SELECT model FROM cars ORDER BY model"; $result = mysql_query($query); while($row = mysql_fetch_assoc($result)) { echo "{$row['mode']}<br>\n"; } Quote Link to comment Share on other sites More sharing options...
amg182 Posted August 28, 2011 Author Share Posted August 28, 2011 Hi, Thanks for reply, I forgot to mention I dont want to use SQL to order ASC or DESC, this code was an example code i knocked up just to find out how it could be done. Really i want to order car models by star rating, but the star rating is not stored in a db table but as a variable. I.E User can specify what order the results are shown. For instance, Highest star rating or lowest star rating. This variable is controled by user input form. Any ideas? other than adding the start ratings to the db table(which isnt really an option for other reasons) THANKS! Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 28, 2011 Share Posted August 28, 2011 Then you should pass parameters to your page to set the field to sort on and the sort order. Then build the ORDER BY part of the query dynamically. You are going about this the wrong way - use MySQL to order the results. $ORDER_BY = ''; if(isset($_GET['sort'])) { $field = mysql_real_escape_string($_GET['sort']); $order = (isset($_GET['order']) && $_GET['order']=="D") ? 'DESC' : 'ASC'; $ORDER_BY = "ORDER BY {$field} {$order}"; } $query = "SELECT model FROM cars {$ORDER_BY}"; Quote Link to comment Share on other sites More sharing options...
amg182 Posted August 28, 2011 Author Share Posted August 28, 2011 Ok, will gives this a go, cheers! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.