php - 使用来自 sql 数据库的 href 和 php 对 html 表进行排序

标签 php html sql sorting html-table

我有一个 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

页面上发生了很多事情,我只包含了生成和显示表格的代码,所以可能是其他原因阻止了它,但我想确保我以正确的方式处理事情在深入研究其余代码之前。

如果您有任何建议,我们将不胜感激。

最佳答案

至于你的 PHP,你可以使用这样的东西:

$product_list = "";    
$order = isset($_GET['sort'])?$_GET['sort']:'date_added';

$query = "SELECT * FROM products ORDER BY $order ";
$sql = mysql_query($query);

while($row = mysql_fetch_array($sql)){

$product_list .= "<tr>
      <td>".$row['id']."</td>
      <td>".$row['product_name']."</td>
      <td>".$row['price']."</td>
      <td>".$row['category']."</td>
      <td>".$row['subcategory']."</td>
      <td>".$row['date_added']."</td>         
        </tr>"; 

}

对于您的 HTML,请确保您包含接收参数的页面名称:

<table class="product-list">
  <tr>
  <th><a href='page.php?sort=id'>ID</a></th>
  <th><a href='page.php?sort=product_name'>Name</a></th>
  <th><a href='page.php?sort=price'>Price</a></th>
  <th><a href='page.php?sort=category'>Category</a></th>
  <th><a href='page.php?sort=subcategory'>Subcategory</a></th>
  <th><a href='page.php?sort=date_added'>Added</a></th>
  </tr>
  <?php echo stripslashes($product_list); ?>
</table>

奖励:

您可以在客户端使用 this 进行排序jquery 插件。

关于php - 使用来自 sql 数据库的 href 和 php 对 html 表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16705530/

相关文章:

javascript - 如何从 Iframe 获取父窗口 URL?

javascript - anchor 标记的数据绑定(bind) href 属性

mysql - 在 SQL 中分解和计数

php - 如何在php函数中使用表单值?

sql - 根据sql中的日期比较返回 "YES"/"NO"

sql - Microsoft 主数据服务 - 何时使用?

php - Hostgator远程访问本地php文件中的数据库

php - 在 PHP 脚本运行时添加加载图像

php - MySQL 和 fputcsv PHP 字段定界符不起作用

php - 转储查询输出是 php 中的空 zip 文件