【问题标题】:How to sort rows of HTML table that are called from MySQL如何对从 MySQL 调用的 HTML 表的行进行排序
【发布时间】:2011-03-30 05:18:21
【问题描述】:

我知道这是一件很基本的事情,但 Google 搜索并没有告诉我如何在单击 th 链接后重新排序行。

我有这个:

<table border="1">
  <tr>
    <th>Type:</th>
    <th>Description:</th>
    <th>Recorded Date:</th>
    <th>Added Date:</th>
  </tr>

<?php 
while($row = mysql_fetch_array($result)){
    ?>
    <tr>
        <td><?php echo $row['type'] ?></td>
        <td><?php echo $row['description'] ?></td>
        <td><?php echo $row['recorded_date'] ?></td>
        <td><?php echo $row['added_date'] ?></td>
    </tr>
    <br /> 


  <?php 
}
mysql_close();
?>
</table>

我需要能够单击type 并按字母顺序排序,然后单击Recorded DateAdded Date 并按日期排序。我看到我需要让 MySQL 查询执行此操作,但我是否将它们设置为带有 a href 标签的条件?

【问题讨论】:

    标签: php mysql html-table


    【解决方案1】:

    最简单的方法是在列标题上放置一个链接,指向同一页面。在查询字符串中,放置一个变量以便您知道他们点击了什么,然后在您的 SQL 查询中使用 ORDER BY 来执行排序。

    HTML 看起来像这样:

    <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 代码中,执行如下操作:

    <?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";
    }
    
    $>
    

    请注意,您不应直接获取 $_GET 值并将其附加到您的查询中。由于某些用户可以访问 MyPage.php?sort=;从我的表中删除;

    【讨论】:

    • 嗯。我收到 Parse 错误:语法错误,第一个“if”语句的意外 T_IS_EQUAL
    • 是的,我的语法可能并不完美。我认为它现在已修复。
    • 我自己无法编辑,但我发现了错误。主要的一个是你需要 $sql 而不是 sql。此外,我的表名在几列上是不同的。但是,谢谢你这样做!它给了我正确的答案!
    • 已编辑以修复语法问题。 PHP 不是我每天都使用的语言。好久没用了那些美元总是让我着迷。我总是觉得必须以特殊字符开头的变量真的很烦人。想不出为什么需要它。我能想到的其他语言都不需要这样的东西。
    • 不错。你可以用这张地图把它弄干一点: $order = array( "type" => array("Type","type"), "desc" => array("Description", "Description"), .. . );循环通过它,您既可以循环生成表头,也可以直接将 order 参数映射到列。
    【解决方案2】:

    这其实很简单,这里有一个可能的方法:

    <table>
        <tr>
            <th>
                <a href="?orderBy=type">Type:</a>
            </th>
            <th>
                <a href="?orderBy=description">Description:</a>
            </th>
            <th>
                <a href="?orderBy=recorded_date">Recorded Date:</a>
            </th>
            <th>
                <a href="?orderBy=added_date">Added Date:</a>
            </th>
        </tr>
    </table>
    <?php
    $orderBy = array('type', 'description', 'recorded_date', 'added_date');
    
    $order = 'type';
    if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
        $order = $_GET['orderBy'];
    }
    
    $query = 'SELECT * FROM aTable ORDER BY '.$order;
    
    // retrieve and show the data :)
    ?>
    

    这样就可以了! :)

    【讨论】:

    • 肯定有NO可能的SQL注入,仔细看!将可能的排序字段列入白名单。
    • 我没有投反对票,但由于某种原因,我不记得当我第一次看到你的答案时支票在那里。但是我可能只是错过了它,而其他一些人可能也错过了它。我比我更喜欢你的风格,所以我也给你一票。
    • @Kibbee 你没把它误认为是 Sarfraz 的尝试吧?哪个他现在被删除了但有 sql 注入问题?
    • 不,我仍然看到 Sarfraz 的回答。我可能已经把 2 弄糊涂了。出于某种原因,我记得查询和 $_GET 的直接连接。我想我只是错过了一些东西,其他人可能也有。
    • 我最喜欢这个答案,但是我只是附加了 DELETE added_date='some date' 并且 SQL INJECTION 删除了记录...有人可以帮助防止这种情况吗???
    【解决方案3】:

    一个简单的表格排序PHP代码:

    (几个值处理和排序的简单表格,使用这个sortable.js脚本)

    <html><head>
    <script src="sorttable.js"></script>
    
    <style>
    tbody tr td {color:green;border-right:1px solid;width:200px;}
    </style>
    </head><body>
    
    <?php
    $First = array('a', 'b', 'c', 'd');
    $Second = array('1', '2', '3', '4');
    
    if (!empty($_POST['myFirstvalues'])) 
    { $First = explode("\r\n",$_POST['myFirstvalues']); $Second = explode("\r\n",$_POST['mySecondvalues']);}
    
    ?>
    
    </br>Hi User. PUT your values</br></br>
    <form action="" method="POST">
    projectX</br>
    <textarea cols="20" rows="20" name="myFirstvalues" style="width:200px;background:url(untitled.PNG);position:relative;top:19px;Float:left;">
    <?php foreach($First as $vv) {echo $vv."\r\n";}?>
    </textarea>
    
    The due amount</br>
    <textarea cols="20" rows="20" name="mySecondvalues" style="width:200px;background:url(untitled.PNG);Float:left;">
    <?php foreach($Second as $vv) {echo $vv."\r\n";}?>
    </textarea>
    <input type="submit">
    </form>
    
    <table class="sortable" style="padding:100px 0 0 300px;">
    <thead style="background-color:#999999; color:red; font-weight: bold; cursor: default;  position:relative;">
      <tr><th>ProjectX</th><th>Due amount</th></tr>
    </thead>
    <tbody>
    
    <?php
    foreach($First as $indx => $value) {
        echo '<tr><td>'.$First[$indx].'</td><td>'.$Second[$indx].'</td></tr>';
    }
    ?>
    </tbody>
    <tfoot><tr><td>TOTAL  = &nbsp;<b>111111111</b></td><td>Still to spend  = &nbsp;<b>5555555</b></td></tr></tfoot></br></br>
    </table>
    </body>
    </html>
    

    来源:php sortable table

    【讨论】:

      【解决方案4】:
      //this is a php file
      
      <html>
      <head>
      <style>
      a:link {color:green;}
      a:visited {color:purple;}
      A:active {color: red;}
      A:hover {color: red;}
      table
      {
          width:50%;
          height:50%;
      }
      table,th,td
      {
          border:1px solid black;
      }
      th,td
      {
          text-align:center;  
          background-color:yellow;
      }
      th
      {
          background-color:green;
          color:white;    
      }
      </style>
      <script type="text/javascript">
      function working(str)
      {
      if (str=="")
        {
        document.getElementById("tump").innerHTML="";
        return;
        } 
      if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
        }
      else
        {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      xmlhttp.onreadystatechange=function()
        {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
          document.getElementById("tump").innerHTML=xmlhttp.responseText;
          }
        }
      xmlhttp.open("GET","getsort.php?q="+str,true);
      xmlhttp.send();
      }
      </script>
      </head>
      <body bgcolor="pink">
      <form method="post">
      <select name="sortitems" onchange="working(this.value)">
      <option value="">Select</option>
      <option value="Id">Id</option>
      <option value="Name">Name</option>
      <option value="Email">Email</option>
      <option value="Password">Password</option>
      </select>
      <?php 
      $connect=mysql_connect("localhost","root","");
      $db=mysql_select_db("test1",$connect);
      $sql=mysql_query("select * from mine");
      echo "<center><br><br><br><br><table id='tump' border='1'>
      <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Email</th>
      <th>Password</th>
      </tr>";
      echo "<tr>";
      while ($row=mysql_fetch_array($sql))
      {?>
      <td><?php echo "$row[Id]";?></td>
      <td><?php echo "$row[Name]";?></td>
      <td><?php echo "$row[Email]";?></td>
      <td><?php echo "$row[Password]";?></td>
      <?php echo "</tr>";
      }
      echo "</table></center>";?>
      </form>
      <br>
      <div id="tump"></div>
      </body>
      </html>
      ------------------------------------------------------------------------
      that is another php file
      
      <html>
      <body bgcolor="pink">
      <head>
      <style>
      a:link {color:green;}
      a:visited {color:purple;}
      A:active {color: red;}
      A:hover {color: red;}
      table
      {
          width:50%;
          height:50%;
      }
      table,th,td
      {
          border:1px solid black;
      }
      th,td
      {
          text-align:center;  
          background-color:yellow;
      }
      th
      {
          background-color:green;
          color:white;    
      }
      </style>
      </head>
      <?php
      $q=$_GET['q'];
      $connect=mysql_connect("localhost","root","");
      $db=mysql_select_db("test1",$connect);
      $sql=mysql_query("select * from mine order by $q");
      echo "<table id='tump' border='1'>
      <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Email</th>
      <th>Password</th>
      </tr>";
      echo "<tr>";
      while ($row=mysql_fetch_array($sql))
      {?>
      <td><?php echo "$row[Id]";?></td>
      <td><?php echo "$row[Name]";?></td>
      <td><?php echo "$row[Email]";?></td>
      <td><?php echo "$row[Password]";?></td>
      <?php echo "</tr>";
      }
      echo "</table>";?>
      </body>
      </html>
      
      
      
      that will sort the table using ajax
      

      【讨论】:

      • 例如,如果我有动态表怎么办。每个记录或行是一个不同的表。这个解决方案是否同样适用?
      【解决方案5】:

      这是使用的最简单的解决方案:

      // 在页面加载时将其用作第一行

      $sort = $_GET['s'];
      

      // 然后简单的按照那个变量排序

      $sql="SELECT * FROM tracks ORDER BY $sort";
      
      echo '<tr>';
      echo '<td><a href="report_tracks.php?s=title">Title</a><td>';
      echo '<td><a href="report_tracks.php?s=album">Album</a><td>';
      echo '<td><a href="report_tracks.php?s=artist">Artist</a><td>';
      echo '<td><a href="report_tracks.php?s=count">Count</a><td>';
      echo '</tr>';
      

      【讨论】:

        【解决方案6】:

        这取决于您的数据的性质。答案因它的大小和数据类型而异。看到很多基于ORDER BY的SQL解决方案。我想建议 javascript 替代品。

        在所有答案中,我没有看到有人提到您未来表格的分页问题。让我们让您更轻松。如果您的表格没有分页,则 javascript 解决方案更有可能使客户端的所有内容都变得整洁干净。如果你认为这个表在你放入数据后会爆炸,你也必须考虑分页。 (每次更改排序列都必须转到第一页)

        另一个方面是数据类型。如果你使用 SQL,你必须小心你的数据类型以及它的排序套件类型。例如,如果您在其中一个 VARCHAR 列中存储整数,则排序不会考虑它们的整数值:您将得到 1, 2, 11, 22 而不是 1, 11, 2, 22

        你可以在 google 上找到 jquery 插件或standalone javascript sortable tables。值得一提的是,HTML5 中的&lt;table&gt; 具有sortable 属性,但显然它还没有实现。

        【讨论】:

          猜你喜欢
          • 2012-10-10
          • 2019-03-28
          • 1970-01-01
          • 2014-06-28
          • 2021-08-27
          • 2014-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多