在高级搜索中使用explode进行搜索时重复的结果

时间:2016-04-17 12:34:55

标签: php

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

问题是如果在第二种情况下两个或多个单词匹配标题,则它会打印重复的书籍。

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

1 个答案:

答案 0 :(得分:1)

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

最终你应该得到或多或少的东西:

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

...