Jump to content

usort mysql


amg182

Recommended Posts

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... ::)

Link to comment
Share on other sites

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";
}

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

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}";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.