Forum Moderators: coopster

Message Too Old, No Replies

Sort by clicking column headers

sorting table results

         

dainstructor

7:18 pm on Feb 26, 2007 (gmt 0)

10+ Year Member



Hey guys,

I'm looking for a way to sort my information once a user clicks on the column header. I've searched this topic and found something that was similar, but not quite what I'm looking to accomplish. I would just like a simple way for users to view the information. Like what is used on many sites including eBay, where if a user clicks on different columns they can sort by those columns. Once or twice depending on if they wanted the information in acsending or descending order.

Does this require the use of Javascript, or can this all be handled in php?

bomburmusicmallet

8:21 pm on Feb 26, 2007 (gmt 0)

10+ Year Member



I use a query string to do this. I make whatever columns are sortable links like samepage.php?sort=thiscolumn. Before I query the database, I check to see if there's a sort value. If not, then I use default order, if there is, then I use that order.

HTH

dainstructor

8:44 pm on Feb 26, 2007 (gmt 0)

10+ Year Member



Thanks bomburmusicmallet,

Works like a charm. However there is one other issue that now arises. Is there a way to make it order by ascending or descending order using this method. For instance, the first time they click on a column header it would sort it in ascending order, and then if they click on that very same column header it would then switch to descending?

Thanks again,

bomburmusicmallet

8:49 pm on Feb 26, 2007 (gmt 0)

10+ Year Member



Yes, there is! Put an arrow image next to the column text and make the image a link, so it would be something like samepage.php?sort=thiscolumn&direction=asc or direction=desc. You could default a direction and put the opposite arrow/link up, and then toggle it if the arrow is clicked on. Just add desc or asc to your query.

HTH

winglian

8:32 pm on Feb 27, 2007 (gmt 0)

10+ Year Member



or you could even do something like

somepage.php?sort__columname=asc&sort__columnname2=desc

<?
foreach ($_POST as $key=>$val) {
$tmp = explode("__", $key);
if ($tmp[0]=='sort') $col[] = array($tmp[1], $val);
}
?>
which would leave you an array of multiple columns to sort by and the direction of sort of each