Page 1 of 1

sorting

Posted: Mon Jan 04, 2010 2:27 pm
by kingdm
Hello everyone.

I have a problem regarding sorting the result of a mysql query. I'll break down the scenario.

Code: Select all

$result = mysql_query("SELECT * FROM users WHERE position_applied LIKE '%$search%' AND age <= $age AND years_exp >= $exp AND status LIKE '%1%'");
This code works fine based on its expected output.

Code: Select all

while($row=mysql_fetch_array($result)) 
{     
        $id = $row['id']; 
        $position = $row['position_applied'];
        $years_exp = $row['years_exp']; 
        $firstname = $row['firstname']; 
        $midname = $row['midname']; 
        $lastname = $row['lastname']; 
        $age = $row['age'];
        $date_membered = $row['date_membered'];
}
And this stores the value to be printed on the table.

All this code works fine. My concern is when it outputs those values, I have a drop down box for them to select how to sort based on the names of the columns outputted by the query. How will I do it?

Re: sorting

Posted: Mon Jan 04, 2010 2:38 pm
by tr0gd0rr
Add an ORDER BY clause to the end of the query based on the drop down selection. Just be sure to allow only valid selections. For example:

Code: Select all

$sortCols = array(
  'position_applied' => 'Position',
  'date_membered' => 'Membership Date',
);
$sort = $_REQUEST['sort'];
if (isset($sortCols[$sort])) {
  $sql .= " ORDER BY $sort";
}

Re: sorting

Posted: Mon Jan 04, 2010 2:52 pm
by kingdm
Thanks for the idea.