SQL排序/排序Php


SQL ORDER BY / Sort Php

我正在努力与我的php,并希望在正确的方向一些帮助。下面是我到目前为止的代码:

    <?php
    $connection = mysql_connect("localhost", "root") or die(mysql_error());
    mysql_select_db("rsi", $connection) or die(mysql_error());
    $query = "SELECT * FROM events"; 
    $result = mysql_query ($query) or die ("error in query"); 
if (mysql_num_rows($result)>0) {
    echo "<table border=1></tr>" .
        "<th>ID</th>" .
        "<th>Name</th>" .
        "<th>Date</th>" .
        "<th>Location</th>" ;
while ($row = @ mysql_fetch_array($result)){
             print "<tr>";
             print "<td>".$row['id']."</td>"; 
             print "<td>".$row['name']."</td>"; 
             print "<td>".$row['date']."</td>"; 
             print "<td>".$row['location']."</td>"; 
             print "</tr>"; 
}
print "</table>";
}

?>

我现在希望通过单击每个/任何标题(例如日期)来从数据库订购结果。感谢您的宝贵时间。

命令结果使用ORDER BY

下面是一个按id排序的例子:

$query = "SELECT * FROM events ORDER BY id";

当你点击一个标题时,你需要让它以某种方式执行新的查询。我把怎么做留了出来,让你们自己去找。通常情况下,您需要重新加载整个页面,并设置排序参数或使用ajax,这将允许您在不重新加载页面的情况下更新页面上的内容。

如果您使用Shakti的答案,我建议不要在查询中直接使用$_GET。我会运行你的$_GET通过某种形式的完整性检查,只允许特定的值,否则你离开你的网站开放的SQL注入攻击。

必须通过列名传递顺序,并通过GET或POST升序或降序传递顺序。下面是一个GET的例子。

$query = "SELECT * FROM events"; 
if(isset($_GET['sort'])
{
    $query.= ' order by '.mysql_real_escape_string($_GET['sort']).' '.mysql_real_escape_string($_GET['order']);
}
$result = mysql_query ($query) or die ("error in query"); 

while ($row = @ mysql_fetch_array($result)){
       print "<tr>";
       print "<td>".$row['id']."</td>"; 
       print "<td>".$row['name']."</td>"; 
       print "<td><a href='http://www.domain.com/currentpageurl?sort=date&order=asc'>".$row['date']."</td>"; 
       print "<td>".$row['location']."</td>"; 
       print "</tr>"; 
    }

我认为您正在寻找在浏览器中排序表。您可能不希望以不同的排序顺序查询数据库中的相同信息。例如:http://tablesorter.com/docs/#Demo

使用tablesorter:

  1. 更改一行代码为:
echo "<table border=1 id="myTable" class="tablesorter"><tr>"
."<th>ID</th>" ."<th>Name</th>" ."<th>Date</th>"
."<th>Location</th></tr>" ;
  • 在正文末尾添加这一行:
  • <script>
        $(document).ready(function() 
            { 
                $("#myTable").tablesorter(); 
            } 
        ); 
    </script>
    
  • 如果你还没有jquery,把它包含在<Head>部分:
  • <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
  • 从http://tablesorter.com/__jquery.tablesorter.zip下载jquery.tablesorter.js

  • 像这样包含jquery.tablesorter.js文件:

  • <script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script>