如何对从MySQL调用的HTML表行进行排序 [英] How to sort rows of HTML table that are called from MySQL
问题描述
我知道这是一个基本的东西,但谷歌搜索没有告诉我如何在点击 th
链接后对行进行重新排序。
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>
我需要点击输入
按字母顺序排序,然后单击记录日期
或添加日期
并按日期排序。我看到我需要让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屋!