簡體   English   中英

PHP多重搜索查詢返回所有行

[英]PHP multiple search query returns all rows

問題是我正在嘗試獲取特定的搜索結果,但是它給出了所有數據庫行,而不是過濾后的結果。 我如何避免這種情況?

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
    }
}
}

您必須從WHERE子句中刪除未使用的字段。 否則, hospital like '%%'條件將有效地匹配表中的每一行。

因此,在您的情況下,您應該動態創建查詢,僅為非空字段添加條件。

當然將結果查詢打印出來非常有幫助 它不僅可以讓您了解正在運行的SQL,還可以使您的問題變得更明智。

嘗試這個:

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);

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM