I want to create a search bar for website but when using "OR" i got error


#1

i got error as mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean from below code

 $search = strtolower($_GET['searchbox']);
  $search =mysqli_real_escape_string($con1,$search);

          $search_exploded = explode ( " ", $search );
                $construct = '';
                 foreach( $search_exploded as $search_each ) {
                    $x="";
			  $x++;
if ($x==1){
    $construct .= "title LIKE '%$search_each%'";
   } else{
     $construct .= " OR title LIKE '%$search_each%'";
               }
                }


$construct="SELECT * FROM vdo WHERE $construct ";
$query=mysqli_query($con1,$construct);
while($row=mysqli_fetch_assoc($query)){
    echo $title=$row['title'];
}

please note that using "AND " insted of "OR" in $construct the code works properly but it matches all searched terms to database column ,i want to match some words from searched term


#2

Try this:

  // REMOVE THESE TWO LINES BEFORE UPLOADING TO SERVER
    ini_set('display_errors', 'true');
    error_reporting(-1);

  $search = strtolower($_GET['searchbox']);
  $search = mysqli_real_escape_string($con1,$search);

  $search_exploded = explode ( " ", $search );

  $construct = '';
  foreach( $search_exploded as $x => $search_each )
  {
    // NOT REQUIRED
      // $x="";
      // $x++;
    if ($x === 0)
    {
      $construct .= "title LIKE '%$search_each%'";
    }else{
      $construct .= " OR title LIKE '%$search_each%'";
    }
  }//
  $construct="SELECT * FROM vdo WHERE $construct ";
  echo '<h1>' .$construct .'</h1>';

  $query = mysqli_query($con1,$construct);
  while( $row=mysqli_fetch_assoc($query) )
  {
    echo $title=$row['title'];
  }

#3

That's because your query doesn't execute, so `mysqli_query() returns false rather than a results object. Did you display the query string to see why not?

This seems a strange set of lines to have all together:

$x="";
$x++;
if ($x==1){

as it appears to mean that $x will always have a value of 1 - you reset it, increment it, then check it. Your reset should surely be before you open the foreach() loop?


#4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.