I brought all values from the db and showed them on a page. Now, if I click the column it should sort ascending or descending.
How do I do this?
I brought all values from the db and showed them on a page. Now, if I click the column it should sort ascending or descending.
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.
desc and asc only. Even better would be to use PDO to avoid it altogether.tr elements to keep track of, JavaScript just isn't feasible for larger datasets?table element on a single page? Are you talking about a paginated table with lots and lots of rows in it?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.
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'])";