在高级搜索中使用爆炸进行搜索时出现重复结果


Duplicate results when searching with explode in advanced search

我正在根据标题进行高级搜索,这是我的代码。首先,我是根据整个标题进行搜索。如果没有找到任何一本书,我会根据书名中的每个单词进行搜索。

问题是,如果第二种情况下有两个或多个单词与标题匹配,那么它就会打印重复的书。

$qry="select * from books where quantity>0 ";
if(isset($title)&&isset($submit1))
$qry.=" and title like '%".$title."%' ";
$books=mysqli_query($con,$qry);
      $numrows=mysqli_num_rows($books);
      if($numrows>0){
        while($row=mysqli_fetch_assoc($books)){
           //print books
        }
      }
      else if(isset($submit1)&&isset($title)){
          $words=explode(" ",$title);
          $notfound=true;
          foreach($words as $value){
              $qry="select * from books where quantity>0 ";
              $qry.=" and title like '%".$value."%' ";
              $books=mysqli_query($con,$qry);
              $numrows=mysqli_num_rows($books);
              if($numrows>0){
                  while($row=mysqli_fetch_assoc($books)){
                       // print based on each word
                  }}

您应该更改SQL查询,使用or一次搜索任何单词,而不是对每个单词进行单独的查询,然后处理重复的单词。只是不要忘记括号,因为你有另一个条件。

最终你应该会得到这样的东西:

$words=explode(" ",$title);
$conditions = [];
foreach ($words as $word) {
    $conditions[] = "title like '%" . $word ."%'";
}
$query = sprintf(
    "select * from books where quantity > 0 and (%s)",
    join(" or ", $conditions)
);
$books = mysqli_query($con, $query);
$numrows = $mysqli_num_rows($books);
...