php - 在表格的 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?
解决方案
您需要添加一个方向变量(如果您的所有代码都在同一个 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);
推荐阅读
- ruby - 增加 gem 搜索路径
- sublimetext3 - 如何定义在 Sublime Text 3 中保存项目的快捷键?
- java - 嵌套对象的简单杰克逊反序列化
- java - 使用 Spring 和 AngularJS 发送电子邮件?
- javascript - 正则表达式从字符串中查找和替换特定元素
- vba - 如何在 VBA 中限制函数?
- c# - 你能有 Zenject 的通用创建方法吗
- php - 在 php 函数中显示错误
- php - PHP - 放置 WooCommerce 后立即获取订单
- android-studio - 当我尝试将数据从 Firebase 导入列表视图时,该应用程序总是崩溃