2016-11-04 3 views
0

문제는 특정 검색 결과를 얻으려고하지만 필터링 된 결과가 아닌 모든 데이터베이스 행을 제공한다는 것입니다. 이걸 어떻게 피할 수 있니?PHP 다중 검색 쿼리가 모든 행을 반환합니다.

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

(!) 참고를 : 주어진 당신이 게시하고 실제 코드가 있다면, 당신은 당신이 조건문을 보강하는 방식으로 구문 분석 오류가되어야 하는지를. –

+0

하나의 조건이 일치하면이 결과를 표시합니다. –

+1

@ Fred-ii- i는 오류가 없지만 모든 데이터베이스 결과를 제공합니다. –

답변

1

WHERE 절에서 사용되지 않은 필드를 제거해야합니다. 그렇지 않으면 hospital like '%%' 조건이 테이블의 모든 행과 효과적으로 일치합니다.

그래서 귀하의 경우에는 비어 있지 않은 필드에 대해서만 조건을 추가하여 즉시 쿼리를 만들어야합니다.

그리고 물론이면 결과 쿼리를 출력하는 데 막대한 도움이 될 것입니다. 그것은 당신에게 어떤 아이디어를 줄 것인지, 어떤 SQL을 실행하는지뿐만 아니라 도 귀하의 질문을 합리적인 것으로 만듭니다.

+0

어떻게 할 수 있습니까? –

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

?> 
관련 문제