问题在于我试图获取特定的搜索结果,但它提供了所有数据库行,而不是过滤结果。我怎么能避免这个?
require_once 'db/connect.php';
if(isset($_GET['submit'])){
$doctor = $db->escape_string($_GET['doctor']);
$specialization = $db->escape_string($_GET['specialization']);
$hospital = $db->escape_string($_GET['hospital']);
$query = $db->query("
SELECT docname, specialization,hospital
From doctor
WHere docname Like '%{$doctor}%' or
specialization like '%{$specialization}%' or
hospital like '%{$hospital}%'
");
?>
<div class="result-count">
Found <?php echo $query->num_rows; ?> results.
</div>
<?php
if($query -> num_rows){
while($r = $query->fetch_object()){
?>
<div class="result-count">
<a href="#"><?php echo $r->docname; ?></a>
</div>
<?php
}
}
}
答案 0 :(得分:1)
您必须从WHERE子句中删除未使用的字段。否则,hospital like '%%'
条件将有效地匹配表中的每一行。
因此,在您的情况下,您应该动态创建查询,仅为非空字段添加条件。
当然它极大地帮助打印出结果查询。它不仅会让您知道,您正在运行什么SQL,还会让你的问题变得合理。
答案 1 :(得分:1)
试试这个:
require_once 'db/connect.php';
if(isset($_GET['submit'])){
$doctor = $db->escape_string($_GET['doctor']);
$specialization = $db->escape_string($_GET['specialization']);
$hospital = $db->escape_string($_GET['hospital']);
$where = array();
if (!empty($doctor)) {
array_push($where, "docname like '%{$doctor}%'");
}
if (!empty($specialization)) {
array_push($where, "specialization like '%{$specialization}%'");
}
if (!empty($hospital)) {
array_push($where, "hospital like '%{$hospital}%'");
}
$sql = "SELECT docname, specialization, hospital "
. "FROM doctor";
if (!empty($where)) {
$sql .= "WHERE " . implode(' OR ', $where);
}
$query = $db->query($sql);
?>