2
votes

Okay so i have managed to implement Sorting when you click the link of the thead. But if i want to change the asc to desc i have to change the code, is there any way using PHP where i can sort the table as descending if its showing as asc?

eg pseudo: If current column is asc then sort desc?

Here is my current code:

if (isset($_GET['sort'])) {
    $sorting = $_GET['sort'];
    $result = $mysqli->query("SELECT * FROM routes ORDER BY $sorting DESC");
}

This is my link structure:

Route ID

To confirm when the user clicks on the link it will sort and if they click the same link again it will sort opposite way.

2

2 Answers

1
votes

You can store the last sort type in sessions.

if (isset($_GET['sort'])) {
    $sorting = $_GET['sort'];

    // check the last sort type used
    $sort = ($_SESSION['last_sort_type'] == 'DESC') ? 'ASC' : 'DESC';

    $result = $mysqli->query("SELECT * FROM routes ORDER BY $sorting $sort");

    // store it in session.
    $_SESSION['last_sort_type'] = $sort;
}

Hope it helps.

1
votes

You can reverse the array, so if they are firstly sorted asc will become desc:

array array_reverse ( array $array [, bool $preserve_keys = false ] )

In order to achieve this:

if (isset($_GET['sort'])) {
    $sorting = $_GET['sort'];
    $result = $mysqli->query("SELECT * FROM routes ORDER BY $sorting DESC"); }

1.- Convert your mysql result resource to an array:

$routes = array();
while ($row = mysql_fetch_array($result)) {
    $routes[] = $row;
}

2.- Reverse the resulting array

  $routes_asc = array_reverse($routes);