sorting

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kingdm
Forum Commoner
Posts: 27
Joined: Thu Dec 03, 2009 9:32 am

sorting

Post 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?
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: sorting

Post 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";
}
kingdm
Forum Commoner
Posts: 27
Joined: Thu Dec 03, 2009 9:32 am

Re: sorting

Post by kingdm »

Thanks for the idea.
Post Reply