0

I want to sort my table by clicking a header of my table, I have already figured out how to do that here : How to sort rows of HTML table that are called from MySQL

However I am wondering, is there away, that by clicking a second time on that button, the sort will go reverse and by clicking a third time back to normal, etc ?

Community
  • 1
  • 1
Lucas Kauffman
  • 6,789
  • 15
  • 60
  • 86
  • Set a boolean GET/POST variable that will adjust the order of your query. Dynamically set the link/submit depending on the boolean value as well. – Josh Jul 22 '11 at 16:01

6 Answers6

3

This can be done like this:

switch($_GET['dir']){

  case "asc":
    $orderBy = " ORDER BY colName ASC"
    break;

  case "desc":
    $orderBy = " ORDER BY colName DESC"
    break;

  default:
    $orderBy = " ORDER BY colName ASC"
    break;
}

$sql = "SELECT FieldNames from MyTable" . $orderBy;

Then you just provide a link with a querystring changing the dir item each time. So your link would become:

<a href="myFile.php?dir=asc">Order ascending</a> 

or

<a href="myFile.php?dir=desc">Order descending</a>

Hope this helps.

aksu
  • 5,221
  • 5
  • 24
  • 39
Dave
  • 1,076
  • 5
  • 15
  • 30
2

You can do this by sending an attribute in url sort=asc , sort=desc. And in php: if($_GET['sort']='asc') sort must be desc. Else sort must be asc.

www.example.com?sort=asc

aksu
  • 5,221
  • 5
  • 24
  • 39
Emil Condrea
  • 9,705
  • 7
  • 33
  • 52
2

Well, if you only want to sort the table then you don't have to reload the page (which might be relatively slow) - there is options to do it client side using JavaScript, ie SortTable by Stuart Langridge

ain
  • 22,394
  • 3
  • 54
  • 74
1

Consider using DataTables, it is very handy.

Tomas
  • 57,621
  • 49
  • 238
  • 373
0

Exactly what you want, is here

https://stackoverflow.com/a/15827728/2220389

with the first click, your table will be sorted ascending, with another click - descending.

Community
  • 1
  • 1
T.Todua
  • 53,146
  • 19
  • 236
  • 237
0

Best way is to change the anchor in header using a JS link:

if(/* current sorting is asc */) {
  document.write("<p>Type".link("mypage.php?sort=desc") + "</p>");
}else if(/* current sorting is desc */) {
  document.write("<p>Type".link("mypage.php?sort=normal") + "</p>");
}else if(/* current sorting is normal */){
  document.write("<p>Type".link("mypage.php?sort=asc") + "</p>");

PHP code will remain the same as in the previous question You asked at SO.

bogatyrjov
  • 5,317
  • 9
  • 37
  • 61