sorting using php
I brought all values from the db and showed them on a page. Now, if I click the column it should sort ascending or descendi开发者_Go百科ng.
How do I do this?
If you want to do this solely in PHP you will need to add parameters onto the query string in the URL.
www.example.com/table.php?col=mycolumn&sort=desc
That would be in the anchor tag for that column, then in table.php
you would have the logic to handle sorting.
You'll be using JavaScript. I suggest sorttable.
Expanding on roflwaffle's post, you will want to use query string vars. From these build a string which you add into your query.
$querySort = array();
if (isset($_GET['colName'])) {
$s = $_GET['colName'];
$snext = '';
switch ($s) {
case '': $snext = 'desc'; break;
case 'desc': $snext = 'asc'; break;
case 'asc': $snext = ''; break;
default: $snext = '';
}
if (!empty ($snext)) {
$querySort[] = "colName $snext";
}
$colName_link = "colName=$snext";
$colName_text = $snext;
}
// Further column checks
if (count($querySort) == 0) {
// Default sort if no sort is given.
$querySort[] = "colName asc";
}
$sort = implode (', ', $querySort);
$query = mysql_query ("SELECT * FROM table ORDER BY $sort");
So given the following query string,
www.example.com/table.php?colName=desc
the query would look like this
SELECT * FROM table ORDER BY colName desc LIMIT 0, 15
and the category link would look like this
echo "<a href='?$colName_link'>Column Name</a> <small>$colName_text</small>";
The best way to do this is by using javascript(no need to refresh page). Yahoo!'s YUI3 has a very nice datatable component. I can not make up from your question if you got the complete dataset on your PHP page but I will assume this for now. You should have a look at YUI3's Column Sorting page to get you started.
Please take a look at THIS link.Check the Example HERE. I use it in one of my project for the same purpose , hope it will help you too.
request: www.example.com/table.php?col=mycolumn&sort=desc
//may be some check , about the column is in the table field
//sort is in the set of (asc , desc)
$q = "select * from mytable where mycond order by addslashes($_GET['mycolumn']) addslashes($_GET['sort'])";
精彩评论