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

I am doing advanced search based on title and here is my code. First I am searching based on whole title. If any of the books are not found I search based on each word present in title.

The problem is if two or more words match title in second case then it prints duplicate books.

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

Instead of doing a separate query for each word and dealing with duplicates after, you should change your SQL query to search for any of the words at once using or. Just don't forget the parentheses as you have another condition there.

Eventually you should end up with something more or less like this:

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

...