A switch between ascending and descending table rows on a tableheader click

A switch between ascending and descending table rows on a tableheader click



I've been messing with this for quite some time now, but I just can't get it to work. What I'm trying to make is ;



A clickable table header, that once clicked switches the row order from ascending to descending and back when clicked again.



The attempts I did so far didn't loop, and got stuck after one click.





How does this relate to PHP? Do you want to do the sorting on server-side? If not, then it's a JavaScript question and should be described as such.
– martynasma
Jul 2 '15 at 8:23





I'm voting to close this question as off-topic because Google has 1 million results for php javascript sort html table
– Hanky Panky
Jul 2 '15 at 8:24


php javascript sort html table





possible duplicate of Sorting HTML table with JS
– martynasma
Jul 2 '15 at 8:24





The thing is that I'm trying to do this without javascript. Just a switch that edits the query from ascending to descending and back on click.
– MTMaas
Jul 2 '15 at 8:32




1 Answer
1



Just add a link to your table header cell which contains a parameter, e.g.


<tr><th>
<a href="currentpage.php?order=<?php echo isset($_GET['order'])?!$_GET['order']:1; ?>">
Name
</a>
</th></tr>



What happens here? A link will be added, containing an order parameter which is set to the opposite of the current order value(1/true or 0/false) or to 1 as default.


order


order



In your PHP script you can now decide how to order your table using the order value:


order


$isAsc = isset($_GET['order'])? (bool) $_GET['order']: 1;



Now you can use the $isAsc boolean:


$isAsc


if ($isAsc)
// Sort data ascending
else
// Sort data descending



Or in a query:


$sql = "SELECT * FROM tabe ORDER BY name ".($isAsc?"ASC":"DESC").";";



Of course, you can extend this idea, e.g., by adding column names to sort by several columns.





Hello Andre, can you kindly help implementing this concept in this question? stackoverflow.com/q/45628071/3446280 thank you for any. But please note that my pages are already .php .
– Robert
Aug 11 '17 at 13:37



.php





Hi Robert. Rudy already updated the given solution, so it combines column and the sorting parameter. If you have further questions or the given solution still does not work for you, feel free to ask!
– André
Aug 15 '17 at 7:38






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Help:Category

How can temperature be calculated given relative humidity and dew point?

I have a recursive function to validate tree graph and need a return condition