首页 > 解决方案 > 如何使用 order by 和 order by desc 对 mysql 表中的行进行排序而不使其过于复杂

问题描述

我找到了一个简单的解决方案,可以按我的 html 表中的每一列进行排序。现在我还希望能够按除 desc 之外的每一列进行排序,但是根据我的解决方案的想法,由于 if 中有两个 if,代码看起来过于复杂。

我想不出另一种可能看起来更好并且总体上更容易的解决方案。

这是我现在的代码:

<th><a href="mypage.php?sort=type">Type:</a></th>
<th><a href="mypage.php?sort=desc">Description:</a></th>
<th><a href="mypage.php?sort=recorded">Recorded Date:</a></th>
<th><a href="mypage.php?sort=added">Added Date:</a></th>
<?php

$sql = "SELECT * FROM MyTable";

if ($_GET['sort'] == 'type')
{
    $sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
    $sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
    $sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
    $sql .= " ORDER BY DateAdded";
}

$>

我的第一个想法是这样的:

$sql = "SELECT * FROM MyTable";

$checkSort = false;
if ($_GET['sort'] == 'type')
{
    if ($checkSort == false)
    {
        $sql .= " ORDER BY type";
        $checkSort = true; 
    }
    if ($checkSort == true)
    {
        $sql .= " ORDER BY type desc";
        $checkSort = false; 
    }
}

我认为它看起来不干净,因为我需要对每一列都这样做,而且我的表将来应该会变成更多列。

标签: phphtmlmysqlsorting

解决方案


您可以尝试直接在通话中发送值。

<th><a href="mypage.php?sort=type&sortType=ASC/DESC">Type:</a></th>
<th><a href="mypage.php?sort=description&sortType=ASC/DESC">Description:</a></th>
<th><a href="mypage.php?sort=daterecorded&sortType=ASC/DESC">Recorded Date:</a></th>
<th><a href="mypage.php?sort=dateadded&sortType=ASC/DESC">Added Date:</a></th>

<?php
$sql = "SELECT * FROM MyTable ORDER BY ".$_GET['sort']." ".$_GET['sortType'];
?>

显然,当您直接将调用传递给 DB 时,您必须进行完整性检查。

注意 - "&sortType=ASC/DESC",只发送 ASC 或 DESC 之一


推荐阅读