【问题标题】:How to sort data tables using the header row by alphabetical order如何使用标题行按字母顺序对数据表进行排序
【发布时间】:2013-10-24 19:28:43
【问题描述】:

我正在做一个 sch 项目,我需要帮助,通过单击标题行按字母顺序对我的数据表进行排序。我使用 MySQL,我打算使用 php 来实现它。谁能帮我?谢谢。

这是我的代码:

这是一个 php 文件。

<?php


  @ $db = new mysqli('localhost', 'f33s01', 'f33s01', 'f33s01');

  if (mysqli_connect_errno()) {
     echo 'Error: Could not connect to database.  Please try again later.';
     exit;
  }

  $query = "select * from gyms";
  $result = $db->query($query);

  $num_results = $result->num_rows;


  echo "<table border=\"3\" cellpadding=\"5\" class=\"dirtable\" style=\"margin-bottom:15px\">
        <tr align=\"center\" class=\"gold\">
        <th>Number</th>
        <th>Gym Name</th>
        <th>Address</th>
        <th>Location</th>
        <th width=\"18%\">Operating Hours</th>
        <th>Reservation</th>
        </tr>";

  for ($i=0; $i <$num_results; $i++) {
     $row = $result->fetch_assoc();

     echo "<tr>";
     echo "<td align=\"center\">".($i+1)."</td>";
     echo  "<td align=\"center\">".stripslashes($row['gymname'])."</td>";
     echo "<td>".stripslashes($row['address'])."</td>";
     echo  "<td>".stripslashes($row['location'])."</td>";
     echo  "<td align=\"center\">".stripslashes($row['operatinghours'])."</td>";
     echo  "<td align=\"center\"><input type= \"submit\" value=\"BOOK NOW\" class=\"bookbutton\"></td>";     
     echo "</td>";   
     echo "</tr>";

  }


      echo "</table>";    
      echo "</form>";


  $result->free();
  $db->close();

?>

【问题讨论】:

  • 您可以为此目的使用 jquery 数据表插件。
  • 你为什么有stripslashes?数据是否在表内转义?您可以使用 htmlspecialchars 之类的东西来逃避来自数据库的潜在 HTML 代码。

标签: php sql sorting


【解决方案1】:

要严格回答您的问题,您可以使用列标题中的链接将 $_GET 变量传递到您的页面,并使用 SORT BY 自定义您的 mysql 查询以呈现数据。我会给出一个粗略的轮廓,这应该会让你指向正确的方向。您需要在标题 url 上添加更多逻辑以启用多个方向的排序。

对于标题:

echo "<th><a href='".$_SERVER[REQUEST_URI]."?orderby=gymname&order=desc'>Gym Name</a>";

然后在你的mysql代码之前,有一个switch语句

switch($_GET[orderby]) {
    case "gymname":
        $filter_orderby = "gymname";
        break;
    case "address":
        $filter_orderby = "address";
        break;
    //...other cases...
}
switch($_GET[order]) {
    case "desc":
        $filter_order = "DESC";
        break;
    case "asc":
        $filter_order = "ASC";
        break;
}

现在,您可以将这些附加到您的查询中:

$myquery = "SELECT * FROM gyms WHERE 1 = 1";
if(isset($filter_orderby) {
    $myquery .= " ORDER BY ".$filter_orderby." ".$filter_order;
}
//Result: SELECT * FROM gyms WHERE 1 = 1 ORDER BY gymname DESC

如果此数据未分页或以其他方式在非平面演示中,那么我同意 Nikita Singh 使用 jQuery 插件的建议 - 另一个是 http://tablesorter.com/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多