开发者

PHP sort tables with click and on another click sort reverse

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 M开发者_开发问答ySQL

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 ?


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.


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


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


Consider using DataTables, it is very handy.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜