rockinaway Posted January 14, 2007 Share Posted January 14, 2007 How can I easily sort data pulled from my database in ascending and descending order when a button a clicked? Link to comment https://forums.phpfreaks.com/topic/34140-sorting-easily-in-ascending-and-descending/ Share on other sites More sharing options...
GingerRobot Posted January 14, 2007 Share Posted January 14, 2007 Firstly, you'll need a link like: <a href='yourpage.php?sort=asc'>Sort Asc</a> and similiarly, <a href='yourpage.php?sort=desc'>Sort Desc</a>Then, on your page, use GET to retrieve the sort method:[code]<?phpif(isset($_GET['sort']){$sort = mysql_real_escape_string($_GET['sort']);$sql = "SELECT * FROM `yourtable` WHERE.... ORDER BY `yourfieldname` '$sort'");mysql_query($sql) or die(mysql_error());}else{//perfrom the query without sorting}//show the data?>[/code]Obviously its just a sample, but without any of your code i cant really help you further. Link to comment https://forums.phpfreaks.com/topic/34140-sorting-easily-in-ascending-and-descending/#findComment-160593 Share on other sites More sharing options...
rockinaway Posted January 14, 2007 Author Share Posted January 14, 2007 Hmm I was doing it that way, however for 4 columns it seems very long, anything shorter? Link to comment https://forums.phpfreaks.com/topic/34140-sorting-easily-in-ascending-and-descending/#findComment-160649 Share on other sites More sharing options...
GingerRobot Posted January 14, 2007 Share Posted January 14, 2007 Do you mean that you want to be able to sort one of 4 columns? In which case, just modify it a little. Make the links like:<a href='yourpage.php?sort=asc&field=field1'>Sort By Field 1 Asc</a>then the code:[code]<?phpif(isset($_GET['sort'] && isset($_GET['field']){$sort = mysql_real_escape_string($_GET['sort']);$field = mysql_real_escape_string($_GET['field']);$sql = "SELECT * FROM `yourtable` WHERE.... ORDER BY `$field` '$sort'");mysql_query($sql) or die(mysql_error());}else{//perfrom the query without sorting}//show the data?>[/code]I dont think you're gonna get shorter for sorting data. And its not that long anyway is it? Link to comment https://forums.phpfreaks.com/topic/34140-sorting-easily-in-ascending-and-descending/#findComment-160682 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.