【问题标题】:Dynamic PHP Table Filter and Sort动态 PHP 表过滤和排序
【发布时间】:2018-12-08 20:45:07
【问题描述】:

我编写了一些 CSS 和 PHP 来查询 MySQL 表。我还有一个下拉框形式的过滤器,它允许用户选择一个“系列”,无论是“电容器”、“电阻器”还是“铁氧体磁珠”(我在下面包含了这个的图片好像)。

我的问题是:一旦元素按家族过滤后,如何为元素创建排序系统?也就是说,如果我想从 MySQL 中查询对应于“电压”的 ASC 值的表,我该怎么做呢?选择排序方法时,我需要保留过滤器。到目前为止,我已将我的代码包含在图像下方。感谢您的帮助!

(下图:1,加载全表:2,仅加载与“capacitor”匹配的系列条目)

代码:(文件名,index.php)

<html>
   <form action="index.php" method="post">
      <select name="family">
         <option value="" selected="selected">Any family</option>
         <option value="capacitor">capacitor</option>
         <option value="resistor">resistor</option>
         <option value="ferrite bead">ferrite bead</option>
      </select>
      <input name="search" type="submit" value="Search"/>
   </form>
   <head>
      <meta charset = "UTF-8">
      <title>test.php</title>
         <style>
            table {
            border-collapse: collapse;
            width: 50%;
            }
            th, td {
            input: "text";
            text-align: left;
            padding: 8px;
            }
            th {
            background-color: SkyBlue;
            }
            tr:nth-child(odd) {background-color: #f2f2f2;}
            tr:hover {background-color: AliceBlue;} 
         </style>
   </head>

<body>
   <p>
   <?php
      $family = "";
      if(isset($_POST['family'])) {
         $family = $_POST['family'];
      }

      try {
         $con= new PDO('mysql:host=localhost;dbname=mysql', "root", "kelly188");
         $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

         if(!empty($family)) {
        $query = 'SELECT * FROM testv2 WHERE family = "'.$family.'"';
         }
         else {
        $query = "SELECT * FROM testv2";
         }

         //first pass just gets the column names
         print "<table>";
         $result = $con->query($query);

         //return only the first row (we only need field names)
         $row = $result->fetch(PDO::FETCH_ASSOC);
         print " <tr>";
         foreach ($row as $field => $value){
        print " <th>$field</th>";
         }
         // end foreach
         print " </tr>";

         //second query gets the data
         $data = $con->query($query);
         $data->setFetchMode(PDO::FETCH_ASSOC);
         foreach($data as $row){
        print " <tr>";
        foreach ($row as $name=>$value){
           print " <td>$value</td>";
        } //end field loop
        print " </tr>";
         } //end record loop
         print "</table>";
      } catch(PDOException $e) {
      echo 'ERROR: ' . $e->getMessage();
      } // end try
   ?>
   </p>
</body>

</html>

【问题讨论】:

  • 能否将您的 PHP 运行后呈现的表格也包含在内?
  • 我对你的要求有点困惑。我包含的图像是在我运行整个脚本之前和之后,包括 PHP。之前,默认加载整个表。之后,进行选择(电容器)并通过使用该过滤器选项查询 MySQL 来过滤表。
  • 对不起,我指的是表格的渲染 HTML。
  • 这些图片是我正在运行脚本的本地主机网站的屏幕截图。这是你的意思吗?
  • 我在我的回答中重新创建了表格。我的意思是最终的 HTML 文本,所以我不必重写它。

标签: php css mysql sorting filter


【解决方案1】:

如果您不想使用专用的表格排序库,您应该可以自己执行此操作。这是一个从提供的数据数组中提取所有数据的解决方案,您应该能够使用 PHP 轻松提供这些数据。

// Initially populate the table
populateTable(data);

// Listen for a click on a sort button
$('.sort').on('click', function() {
  // Get the key based on the value of the button
  var key = $(this).html();
  // Sort the data and update our data
  data = sortBy(data, key);
  // Fill the table with our data
  populateTable(data);
});

// Modified from: https://www.sitepoint.com/sort-array-index/
function sortBy(inputData, key) {
  // Sort our data based on the given key
  inputData.sort(function(a, b) {
    var aVal = a[key],
      bVal = b[key];
    if (aVal == bVal) return 0;
    return aVal > bVal ? 1 : -1;
  });
  
  return inputData;
}

// Modified from: https://stackoverflow.com/questions/5361810/fast-way-to-dynamically-fill-table-with-data-from-json-in-javascript
function populateTable(inputData) {
  var keys = new Array(),
    i = -1;

  // Create an array of keys
  $.each(inputData[0], function(key, value) {
    keys[++i] = key;
  });

  var r = new Array(),
    j = -1;

  // Populate the table headers
  r[++j] = '<tr>';
  $.each(keys, function(key, value) {
    r[++j] = '<th>' + keys[key] + '</th>';
  });
  r[++j] = '</tr>';

  for (var index = 0, size = inputData.length; index < size; index++) {
    // Populate the table values
    r[++j] = '<tr>';
    $.each(keys, function(key, value) {
      r[++j] = '<td>' + inputData[index][value] + '</td>';
    });
    r[++j] = '</tr>';
  }

  // Join everything together
  $('#data-table').html(r.join(''));
}
table {
  border-collapse: collapse;
  width: 100%;
}

th,
td {
  text-align: left;
  padding: 8px;
}

th {
  background-color: skyblue;
}

tr:nth-child(odd) {
  background-color: #f2f2f2;
}

tr:hover {
  background-color: aliceblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
  // Set our data
  var data = [{
      ID: 1,
      Family: 'resistor',
      Capacitance: 7,
      Voltage: 6,
      Price: 25.6
    },
    {
      ID: 2,
      Family: 'capacitor',
      Capacitance: 10,
      Voltage: 10,
      Price: 100.2
    },
    {
      ID: 3,
      Family: 'ferrite bead',
      Capacitance: 1,
      Voltage: 5,
      Price: 35.6
    },
    {
      ID: 4,
      Family: 'resistor',
      Capacitance: 1,
      Voltage: 4,
      Price: 35.6
    },
    {
      ID: 5,
      Family: 'capacitor',
      Capacitance: 9,
      Voltage: 4,
      Price: 25.6
    }
  ];
</script>


<table id="data-table"></table>

<p>Sort by:</p>
<button class="sort">ID</button>
<button class="sort">Family</button>
<button class="sort">Capacitance</button>
<button class="sort">Voltage</button>
<button class="sort">Price</button>

【讨论】:

  • 哇,感谢您提供的详细信息!我很快就会尝试这个:)
  • 没问题!这也是对我自己进行排序的一个很好的复习。如果您需要任何解释或建议,请随时发表评论。
【解决方案2】:

以下是对表格进行数字排序的方法:
1) 给预期的表一个 ID(在我的代码案例中,它是主表)
2)每次点击表头调用排序函数(包括列号,第一个为0,每次添加更多列,函数名内的数字加一,本例为sortTable(0),sortTable(1 ),....
最终结果将是这样的(测试这个例子,它可以工作):

<table id="main-table">
  <tr>
    <th style="cursor:pointer" onclick="sortTable(0)">colomn 0</th>
    <th style="cursor:pointer" onclick="sortTable(1)">colomn 1</th>
    <th style="cursor:pointer" onclick="sortTable(2)">colomn 2</th>
    <th style="cursor:pointer" onclick="sortTable(3)">colomn 3</th>
    <th style="cursor:pointer" onclick="sortTable(4)">colomn 4</th>
  </tr>
  <tr>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
  </tr>
   <tr>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
  </tr>
   <tr>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
  </tr>
   <tr>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
  </tr>
   <tr>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
    <td><?php echo  rand(0,999);?></td>
  </tr>

</table>

<script>
function sortTable(column) {
  var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("main-table");
  switching = true;
  while (switching) {
    switching = false;
    rows = table.getElementsByTagName("TR");
    for (i = 1; i < (rows.length - 1); i++) {
      shouldSwitch = false;
      x = rows[i].getElementsByTagName("TD")[column];
      y = rows[i + 1].getElementsByTagName("TD")[column];
      if (Number(x.innerHTML) > Number(y.innerHTML)) {
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
    }
  }
}
</script>

这是生成列号所需的操作:

$counter = 0;
foreach ($row as $field => $value){
print " <th onclick='sortTable($counter)'>$field</th>";
$counter = $counter+1;
}

【讨论】:

  • 哈哈,怎么又打招呼了!您的方法看起来不错,但我的一个问题是我没有预定义的列标题。它们与表的其余部分作为单行动态加载。我不能告诉他们每个人单独运行 sortable(column) 函数。
  • 只要放在页面的页脚,就在
【解决方案3】:

您可以在表单中添加排序下拉列表并在查询中使用它。这样,您可以让用户选择一种排序方法并在服务器端处理它。

<form action="index.php" method="post">
      <select name="family">
         <option value="" selected="selected">Any family</option>
         <option value="capacitor">capacitor</option>
         <option value="resistor">resistor</option>
         <option value="ferrite bead">ferrite bead</option>
      </select>
      <select name="sort">
         <option value="" selected="selected">Any Order</option>
         <option value="ASC">Ascending</option>
         <option value="DESC">Descending</option>
      </select>
      <input name="search" type="submit" value="Search"/>
   </form>

在 PHP 中:

<?php
      $family = "";
      $sort = "";
      if(isset($_POST['family'])) {
         $family = $_POST['family'];
      }

在你的 if 语句中:

if(!empty($family)) {
        $query = 'SELECT * FROM testv2 WHERE family = "'.$family.'" ORDER BY "'.$sort'"';
         }
         else {
        $query = "SELECT * FROM testv2";
         }

【讨论】:

  • 感谢您的建议。我想我以前尝试过这种方法,并且因为 $_POST 方法每次脚本运行只能选择一个选择,不幸的是它会摆脱用户过滤器选择,并在选择排序选项时再次加载整个表......
  • @Jonny1998 我更像是一名 C# 开发人员。在 C# 中使用数据集执行此操作是一个非常强大的解决方案,因为它为您提供了更多控制权。不幸的是,PHP 没有数据集结构。但是,using arrays in PHP,您几乎可以做类似的事情。当然这是一个学习曲线,但是我们每天都在学习
【解决方案4】:

Datatables https://datatables.net/ 也很酷。正常功能是使用 JavaScript,但您可以将其配置为使用服务器资源并在服务器上处理日期并仅显示结果。一旦掌握了窍门,就很容易了。

每次排序或过滤数据时,datatable 都会发送一个包含所有必要信息的数组,因此您只需扫描数组并相应地生成查询。

【讨论】:

    【解决方案5】:

    您可以将 $_POST['family'] 保存在隐藏字段中(可能是 $_POST['hidden_​​family'])。当您进行下一级搜索时,您可以检查它,如果它不为空,则每次都将其附加到您的搜索中。

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 2013-04-18
      • 1970-01-01
      • 2021-09-03
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2019-03-31
      相关资源
      最近更新 更多