如何对从MySQL调用的HTML表行进行排序

Joe*_*oel 16 php mysql html-table

我知道这是一个基本的东西,但谷歌搜索没有告诉我如何在点击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>
Run Code Online (Sandbox Code Playgroud)

我需要能够按type字母顺序单击和排序,然后单击Recorded DateAdded Date按日期排序.我看到我需要让MySQL查询这样做,但我是否将它们设置为带a href标签的条件?

Kib*_*bee 43

最简单的方法是在列标题上添加一个链接,指向同一页面.在查询字符串中,放置一个变量,以便您知道它们单击了什么,然后在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>
Run Code Online (Sandbox Code Playgroud)

在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";
}

$>
Run Code Online (Sandbox Code Playgroud)

请注意,您不应直接获取$ _GET值并将其附加到查询中.有些用户可以使用MyPage.php?sort =; 从MyTable中删除;


Gui*_*iks 40

这实际上非常简单,这是一种可能的方法:

<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 :)
?>
Run Code Online (Sandbox Code Playgroud)

那就行了!:)

  • 肯定**NO**可能的SQL注入,看起来更接近!将可能的字段列入白名单. (3认同)