I've this php script that displays information stored in a MYSQL DB..
it shows the data in a tabular format..

What i'm trying to do is to make php sort the data in the table according to what user specifies (by clicking a link that sends a value using GET)..

$sort = $_GET['sort_by'];

i've this code for the default order of the information:

$query = "SELECT `rego`, `make`, `model`, `color`, `kms`, `year`, `adprice`, `branch`, `state`, `saleprice`, `salesperson` FROM `vehicles` ";
  $result = mysql_query($query);

and this one for when a user specifies what way to sort the info:

$order = "SELECT `rego`, `make`, `model`, `color`, `kms`, `year`, `adprice`, `branch`, `state`, `saleprice`, `salesperson` FROM `vehicles` ORDER BY `vehicles`.`$sort` ASC LIMIT 
0, 30 ";
 $orderresult = mysql_query($order);

i'm using a "while" loop to display all the data from the DB..

while ($row =  mysql_fetch_assoc($result)) {

what i'd like to do is to set the while loop to use "$row = mysql_fetch_assoc($result)" for the default order and to use $row = mysql_fetch_assoc($orderresult) when user specfies what way to sort info.

Recommended Answers

All 6 Replies

Start by setting $sort to some default value, say 0, before you try to retrieve it from the $_GET array. Then immediately before your while loop, you could do something like:

if ($sort != 0)
{
  $result = $orderresult;
}
ORDER BY `vehicles`.`$sort` ASC LIMIT

You may want change that DOT between `vehicles` and `$sort` to a comma.

Thanks mate,

it helped a lot..

cheers..

You may want change that DOT between `vehicles` and `$sort` to a comma.

Hi there,

thanks for your reply Hazard..

could you please explain why is that?

thanks again

In fact you don't need to, but it would probably read better if you got rid of the 'vehicles'. You don't need to explicitly specify the table for the sort operation because you are only getting your data from a single table. If you were using a join or otherwise accessing more than one table, then it is necessary to specify the table.

HazardTW is incorrect, a comma will make your SQL invalid. I think he/she thought that you were trying to sort by more than one column, rather than by a column in the specified 'vehicles' table.

Sorry about that!

It was late, I was tired, didn't realize that `vehicles` was the table name, thought he was trying to sort by multiple fields, ie. `vehicles` field, then `$sort` field.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.