使用 PHP 对 mySQL 查询的结果重新排序,而无需执行其他查询

发布于 2024-09-13 08:54:53 字数 1436 浏览 8 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

睡美人的小仙女 2024-09-20 08:54:53

我可能会使用某种客户端脚本来完成此操作,我知道有多种 JavaScript 或 DHTML 选项。这些将为您的用户更快地执行(无论如何在大多数机器上),并避免对数据库不必要的点击。我想我最后看的是这个: http://www.kryogenix.org/ code/browser/sorttable/

但是如果你真的有兴趣用你的 SQL 查询来做这件事...所以你的表中有结果,类似于:

<table>
<tr>
<th><a href='page.php?orderby=name'></th>
<th><a href='page.php?orderby=blah'></th>
....
</table>

然后在构建查询时,你可以简单地做一些事情就像:

<?php
$sql = "select * from sometable";
switch ( $_REQUEST['orderby'] ) {
    case "name": $sql .= " order by name"; break;
    case "blah": $sql .= " order by blah"; break;
    default: $sql .= " order by whatevercolumnyouwantasdefault";
}
...
?>

或者甚至像这样简单,假设您已经检查了 $_REQUEST 值并确定它们是合法的:

<?php
$sql = "select * from sometable";
if ( isset($_REQUEST['orderby']) )
    $sql .= " order by ".$_REQUEST['orderby'];
else
    $sql .= " order by whatevercolumnyouwantasdefault";
?>

I would probably do this with some sort of client-side script, I know there are several JavaScript or DHTML options out there. These would be executed much more quickly for your users (on most machines, anyway) and avoid unnecessary hits to the database. I think the last one I looked at was this: http://www.kryogenix.org/code/browser/sorttable/

But if you're really interested in doing it with your SQL query...so you have your table with results, something similar to:

<table>
<tr>
<th><a href='page.php?orderby=name'></th>
<th><a href='page.php?orderby=blah'></th>
....
</table>

Then when constructing the query, you could simply do something like:

<?php
$sql = "select * from sometable";
switch ( $_REQUEST['orderby'] ) {
    case "name": $sql .= " order by name"; break;
    case "blah": $sql .= " order by blah"; break;
    default: $sql .= " order by whatevercolumnyouwantasdefault";
}
...
?>

Or even something as simple as this, assuming you've checked the $_REQUEST values and determined they are legitimate:

<?php
$sql = "select * from sometable";
if ( isset($_REQUEST['orderby']) )
    $sql .= " order by ".$_REQUEST['orderby'];
else
    $sql .= " order by whatevercolumnyouwantasdefault";
?>
木緿 2024-09-20 08:54:53

也许您可以将结果存储在某种数组中。

编辑:
否则,您可以使用 JavaScript 对表进行排序,而无需刷新页面。这是一个 jQuery 插件,可以为您完成此操作。

Perhaps you could store the results in some sort of array.

EDIT:
Otherwise you can use JavaScript to sort the table without having to refresh the page. Here is a jQuery plugin that can do this for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文