1

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.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
MTMaas
  • 63
  • 1
  • 5
  • 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 02 '15 at 08:23
  • 1
    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 02 '15 at 08:24
  • possible duplicate of [Sorting HTML table with JS](http://stackoverflow.com/questions/14267781/sorting-html-table-with-js) – martynasma Jul 02 '15 at 08: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 02 '15 at 08:32

1 Answers1

2

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.

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

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

Now you can use the $isAsc boolean:

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.

André
  • 477
  • 3
  • 11
  • Hello Andre, can you kindly help implementing this concept in this question? https://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
  • 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 07:38