【发布时间】:2019-08-18 02:24:39
【问题描述】:
我找到了一个简单的解决方案,可以按我的 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;
}
}
我认为它看起来不干净,因为我需要对每一列都这样做,而且我的表将来应该会变成更多列。
【问题讨论】:
-
所以你正在寻找代码优化?对
-
@devpro 好吧,是的,我还是个初学者,想不出其他更好的解决方案,我想也许有人知道我应该怎么做
-
@Xxy :另一种解决方案是使用database
-
@PraveenKumar 我以前从未使用过数据库,所以我需要先阅读如何包含和使用它。但我也想自己学。
-
你还想按 DESC 顺序排序吗?