php - 如何使用 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;
}
}
我认为它看起来不干净,因为我需要对每一列都这样做,而且我的表将来应该会变成更多列。
解决方案
您可以尝试直接在通话中发送值。
<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 之一
推荐阅读
- reactjs - 尝试从 React Web 应用程序获取数据并进入 Electron 应用程序以显示徽章计数
- jquery - Jquery 在 elecron.js 中无法正常工作
- php - Laravel - 完成后仍在内存中的作业处理方法
- java - Snackbar.setAnchorView(不工作);
- javascript - 分配失败 - JavaScript 堆内存不足
- c# - 使用“.NETFramework,Version=v4.6.1”恢复包“MyPackage 1.0.1”,自定义 nuget 包上的警告
- c - 当该函数位于另一个文件夹中的另一个 c 程序中时,如何使用 gdb ddebugger 进入该函数?
- javascript - 在 REST 中使用异步函数的原因是什么?
- ios - XCTest 测试用例失败,出现错误“无法安装或启动测试运行程序”。(根本错误:无法连接到设备)
- matlab - 如果输入错误的输入,如何将用户重定向回开始