首页 > 解决方案 > 在表格的 ASC 和 DESC 排序之间切换

问题描述

这是我正在排序的列:

<th><a href="?sort=date">Dato</a></th>

这就是我的排序方式:

$sql = "SELECT * FROM table";
                  
if ($_GET['sort'] == 'date')
{
    $sql .= " ORDER BY date DESC";
}
                  
$result = $link->query($sql);

当用户再次按下该列时,如何添加它ORDER BY date ASC而不是 DESC?

标签: phphtml

解决方案


您需要添加一个方向变量(如果您的所有代码都在同一个 PHP 文件中,这可能会更简单)

<?php

$direction = 'ASC'; // default

if($_GET['direction'] == 'ASC'){
      $direction = 'DESC';
}

echo '<a href="?sort=date&direction='.$direction.'">Dato</a>';

?>

然后只需将 $direction 变量与您的查询连接起来。

$sql = "SELECT * FROM table";
                  
if ($_GET['sort'] == 'date')
{
    $sql .= " ORDER BY date "; //removed your DESC from here, please note!!
}
if ($_GET['direction'])
{
    $direction = ($_GET['direction']=='ASC' ? 'ASC' : 'DESC');
    $sql .= " ".$direction;
}
              
$result = $link->query($sql);

推荐阅读