我有一个 html 表,其中包含来自用 php 吐出的 sql 表的产品数据。我想通过单击表格列的标题对数据进行排序。
我像这样输出我的表(php)
$product_list = "";
$sql = mysql_query("SELECT * FROM products ORDER BY date_added DESC");
$product_list .= "<tr>
<td>$id</td>
<td><strong>$product_name</strong></td>
<td>$$price</td>
<td>$category</td>
<td>$subcategory</td>
<td>$date_added</td>
</tr>";
html
<table class="product-list">
<tr>
<th><a href='?sort=id'>ID</a></th>
<th><a href='?sort=product_name'>Name</a></th>
<th><a href='?sort=price'>Price</a></th>
<th><a href='?sort=category'>Category</a></th>
<th><a href='?sort=subcategory'>Subcategory</a></th>
<th><a href='?sort=date_added'>Added</a></th>
</tr>
<?php echo stripslashes($product_list); ?>
</table>
我已经从在线示例中尝试了几种方法来做到这一点,但是当我单击标题时没有任何反应。
这是我测试过的东西
$sort = array('id', 'product_name', 'price', 'category', 'subcategory', 'date_added');
$order = '';
if (isset($_GET['sort']) && in_array($_GET['sort'], $sort)) {
$order .= $_GET['sort'];
}
$query = 'SELECT * FROM products ORDER BY '.$order;
// Then Output the table as above
页面上发生了很多事情,我只包含了生成和显示表格的代码,所以它可能会阻止这个,但我想确保在深入研究之前我以正确的方式做事其余的代码。
任何建议您将如何解决此问题将不胜感激。