"Sort by" Box for Lists

By Hawkee on Mar 24, 2008

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>

Comments

Sign in to comment.
CreativeDesign   -  Nov 18, 2013

Hawkee is great ^_^

 Respond  
PHP amatuer   -  Mar 08, 2012

Thank you so much. It helps me a lot !!!

Ghufran  -  Apr 22, 2013

plz any one help me this code isn't working :(

Sign in to comment

eby1   -  Nov 13, 2008

great work

Ghufran  -  Apr 22, 2013

plz any one help me this code isn't working :(

Sign in to comment

DarkDaemon   -  Mar 24, 2008

i love it :D Humps Hawkee\'s Head 9/10

Ghufran  -  Apr 22, 2013

plz any one help me this code isn't working :(

Sign in to comment

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.