MTMaas
MTMaas

Reputation: 63

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.

Upvotes: 1

Views: 7326

Answers (1)

André
André

Reputation: 477

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.

Upvotes: 2

Related Questions