This code produces a sort box for any number of arbitrary criteria on any type of data you have in your database. For this particular example we've got a product sort where users can sort by price or name.
The hidden param1 and param2 variables are arbitrary. In this example they could be a search query and category id.
This also includes a javascript auto-submit so users don't need to click a "Go" or "Sort" button after making their selection.
You can find this code in action here:
http://www.hawkee.com/shop/cat/2801/
<?php
$selected = array();
$orderby = $_GET[orderby];
if(!$orderby) { $orderby = 'price_asc'; }
if($orderby == 'price_asc')
{
$orderby_query = "order by price asc";
}
else if($orderby == 'price_desc')
{
$orderby_query = "order by price desc";
}
else if($orderby == 'name')
{
$orderby_query = "order by name";
}
else { unset($orderby); }
// If $orderby was valid set the selected sort option for the form.
if($orderby)
{
$selected[$orderby] = 'selected';
}
// Now run your SQL query with the $orderby_query variable. Ex:
$query = "select * from products $orderby_query";
// SQL code goes here..
?>
Sort by
<form method=get style="display: inline;" name='orderby_form'>
<input type=hidden name='param1' value="<?php print $param1; ?>">
<input type=hidden name='param2' value="<?php print $param2; ?>">
<select name=orderby onChange="orderby_form.submit();">
<option value='name' <?php print $selected[$orderby]; ?>>Name</option>
<option value='price_asc' <?php print $selected[$orderby]; ?>>Price (Low - High)</option>
<option value='price_desc' <?php print $selected[$orderby]; ?>>Price (High - Low)</option>
</select>
</form>
plz any one help me this code isn't working :(