我编写了一些 PHP 和 CSS 来查询在 WAMP 服务器上运行的 MySQL 数据库表。我有两个运行的文件,index.php 和 test.php。 Index 包含一个选择器框,允许用户从“family”中选择一个过滤器选项。最后,我希望将选定的选项实现到 SELECT 查询中,该查询确定 test.php 的 PHP 部分中的数据输出。
例如,如果用户从 index.php 中选择“capacitor”,我需要创建的表仅显示与“capacitor”匹配的系列条目(以及所有相应的详细信息,如“capacitor”, “电压”和“价格”)。目前,我的 PHP 只获取整个表(例如下图)。
我知道我需要使用 $_POST super 全局来获取用户输入并将其放入 SELECT 查询中,但我不确定如何操作。
编辑:当我尝试使用 WHERE 修饰符缩小返回数据的范围时,我收到以下错误
错误:SQLSTATE[42S22]:未找到列:1054“where 子句”中的未知列“电容器”
下面是index.php
<form action="test.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>
</html>
下面是test.php
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>test.php</title>
<style>
table {
border-collapse: collapse;
width: 50%;
}
th, td {
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
try {
$con= new PDO('mysql:host=localhost;dbname=mysql', "root", "kelly188");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM testv2";
//first query 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 loop
print " </tr>";
//second query gets the data
$data = $con->query(**PERTAINS TO EDIT**);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} //end row loop
print " </tr>";
} //end record loop
print "</table>";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try
?>
</p>
</body>
</html>
最佳答案
您必须捕获请求的家庭:
$filter_key = "";
if(isset($_POST['family'])){
$filter_key = $_POST['family'];
}
他们必须使用设置的过滤器来符合您的查询:
if(!empty($filter_key))
$query = 'SELECT * FROM testv2 WHERE family = "'.$filter_key.'"';
else
$query = 'SELECT * FROM testv2';
关于php - 关于从 MySQL 中获取 PHP 数据表的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51088582/