我写了一些 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>
原文由 Jonny1998 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您不想使用专用的表格排序库,您应该可以自己执行此操作。这是一个从提供的数据数组中提取所有数据的解决方案,您应该能够使用 PHP 轻松提供这些数据。