我有一个用于在SQL表中搜索的PHP搜索表单。 所有这一切都很有效,但有一件事我想改变。
在搜索之前,整个表格都会显示在屏幕上。 我想在搜索后仅提及记录。
有人知道用PHP隐藏表吗? 非常感谢提前!
HTML
<form action="" method="post">
<input type="text" name="search" placeholder="Search">
<input type="submit" value="Submit" />
</form>
PHP
<?php
$host = "******";
$user = "******";
$password = "******";
$database_name = "vangsten";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
$search=$_POST['search'];
$query = $pdo->prepare("select * FROM meldingen WHERE soort LIKE '%$search%' OR zone LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0) {
echo "<table style=\"margin:50px auto;\">";
echo "<tr><td>VISSOORT</td><td>LENGTE</td><td>AANTAL</td><td>ZONE</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td>";
echo $results['soort'];
echo "</td><td>";
echo $results['lengte'];
echo "</td><td>";
echo $results['aantal'];
echo "</td><td>";
echo $results['zone'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
答案 0 :(得分:0)
您可以检查用户是否点击了搜索按钮:
if (isset($_POST['search'])) {
// do your table generation here
}
答案 1 :(得分:0)
这是因为即使没有搜索过,您也会最终运行查询:WHERE sort LIKE '%%'
您应该检查是否先通过了搜索
if(array_key_exists('search',$_POST) && !empty($_POST['search'])){
$search=$_POST['search'];
$query = $pdo->prepare("select * FROM meldingen WHERE soort LIKE '%$search%' OR zone LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0) {
echo "<table style=\"margin:50px auto;\">";
echo "<tr><td>VISSOORT</td><td>LENGTE</td><td>AANTAL</td><td>ZONE</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td>";
echo $results['soort'];
echo "</td><td>";
echo $results['lengte'];
echo "</td><td>";
echo $results['aantal'];
echo "</td><td>";
echo $results['zone'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
}
array_key_exists('search',$_POST)
检查是否有值
关键'搜索;' !empty($_POST['search'])
检查它不仅仅是
一个空字符串。 (你可能想允许这个)您可以使用isset($_POST['search'])
代替array_key_exists('search',$_POST)
,但array_key_exists
是更好的做法,因为isset
如果值为NULL