如何对从 MySQL 调用的 HTML 表的行进行排序 [英] How to sort rows of HTML table that are called from MySQL

查看:29
本文介绍了如何对从 MySQL 调用的 HTML 表的行进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know it's such a basic thing, but a Google search hasn't shown me how to re-sort the rows after clicking the th links.

我有这个:

<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 标签的条件?

I need to be able to click type and sort alphabetically, and click on either Recorded Date or Added Date and sort by date. I see that I need to have the MySQL queries do this, but do I set them up as conditionals with a href tags?

推荐答案

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

The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.

HTML 看起来像这样:

The HTML would look like this:

<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 代码中,做这样的事情:

And in the php code, do something like this:

<?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=;从 MyTable 中删除;

Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;

这篇关于如何对从 MySQL 调用的 HTML 表的行进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆