Top

"Sort by" Box for Lists


PHP Code
+ 1 likes
Please Register to submit score.
Bookmark and Share
Average Score  9.0 (of 1 scores)
Date Added  Mar 24, 2008
Last Updated  Mar 24, 2008
Tags  database  mysql  search  sort 

Introduction

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/

Grab the Code

<?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

  (2)  RSS
DarkDaemon
Comments: 49
 
PHP Snippet:  "Sort by" Box for Lists
Posted on Mar 24, 2008 2:48 am
i love it :D *Humps Hawkee's Head* 9/10
eby1
Comments: 1
 
PHP Snippet:  "Sort by" Box for Lists
Posted on Nov 13, 2008 4:38 am
great work

Commenting Options

Register or Login to Hawkee.com or use your Facebook or Twitter account by clicking the corresponding button below.

  
Bottom