user1658170 user1658170 - 12 days ago 8
PHP Question

Reverse search order by clicking on table header

I have a table that displays from MYSQL in an ordered fashion. I am trying to get it so that if I click the header link it will reverse the order and then if I click it again it will revert to the original case. I am getting stuck on trying to revert it. Here is what I have so far:

switch($_GET['sort']){

case "asc":
$orderBy = "ORDER BY whole_date asc";
break;

case "desc":
$orderBy = "ORDER BY whole_date desc";
break;

default:
$orderBy = "ORDER BY whole_date desc";
break;
}


Referred to in the the SQL statement here:

...WHERE user_id = '$username'".$orderBy." LIMIT $offset, $rowsperpage ";


In my table header I have the link like this in HTML:

<th><a href='view.php?sort=desc'>header</a></th>


This is where my problem is, how would I get it to revert back. How would I include a sort=asc link?

Answer
printf('<a href="view.php?sort=%s">header</a>',
       empty($_GET['sort']) || $_GET['sort'] == 'asc' ? 'desc' : 'asc');