0

I'm trying to get my search form to search for multiple terms.For example "Black dog".In my $keywords they are separated with commas (Black, dog).I know that i can just enter (Black dog, ) in my $keywords but I want them to be separated with commas.If I put single term (dog) it returns result for only that term.If I put 2 (Black dog) it returns 0 results.

<form class="form-inline pull-xs-right" action="search.php" method="POST" >
    <input class="form-control" type="text" name="search" placeholder="Search">
    <button class="btn btn-success-outline" name="searchh" type="submit" value=">>" >Search</button>
  </form>  
<?php
$i=null;
$search=null;
$result_query=null;

if(isset($_POST['search'])){

    $get_value = addslashes($_POST['search']);

    $search = mysqli_real_escape_string($con,"$get_value");
    ?>
      <h2>Showing results for
     <?php echo $_POST['search'] ?></h2>
      <?php
if($search==''){

echo "<center><b>Please write something in the search box!</b></center>";
exit();
}

 $search = $_POST['search']; 
 $terms = explode(" ", $search);
 foreach ($terms as $each) {
   $i++;

   if ($i == 1)
       $result_query .= "keywords LIKE '%$each%' ";
   else
       $result_query .= "OR keywords LIKE '%$each%' ";

 }

$result_query = "SELECT * FROM content WHERE keywords LIKE '%".$search."%'";

$run_result = mysqli_query($con,$result_query);
// echo mysqli_num_rows($run_result);
// exit;
 if(mysqli_num_rows($run_result)<1){
echo "<center>Sorry no matches found</center>";
exit();

}


while($row_result=mysqli_fetch_array($run_result))
{

    $name=$row_result['name'];
    $keywords=$row_result['keywords'];
    $image=$row_result['image'];
    $link=$row_result['link'];

   ?>
MarkP
  • 1
  • 1
  • 2
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Aug 03 '16 at 19:57
  • You could explode the array of search words and do an OR condition in your query with the exploded array. – Jay Blanchard Aug 03 '16 at 19:58
  • `WHERE keywords LIKE "%Black%" and LIKE "%dog%"` – splash58 Aug 03 '16 at 19:59
  • Explode will work fine , thank you. – MarkP Aug 03 '16 at 20:05

0 Answers0