Search code examples
phpmysqlsearchbarkeyword-search

Search Bar coding for multiple keywords when only 1 matches


So I have looked around the internet and actually signed up to this site since i find most my google searches wind me up here. I am almost done making my website and I used a template that I expanded. It has a search bar on it that wasn't functioning. I have got it working mostly. the problem I am having is that when I put in a keyword that MySQL has it works fine, when I put in a lone keyword that I know doesn't exist it give a proper no results response. Now my problem is when you mix the 2 up it errors out the database. Here is my php code that I've put together so far...

    <?php
$db = mysqli_connect('host','username','password')
or die('Error connecting to MySQL server.');
$keyword = $_GET['keyword'];
$terms = explode(" ", $keyword);

$query = "SELECT * FROM searchresults WHERE ";

foreach ($terms as $each) {

    $i=0;
    if ($i == 0)
    $query .= "pagebody LIKE  '%$each%' ";
    else
    $query .= " OR pagebody LIKE  '%$each%' ";

}

mysqli_query($db, $query) or die('Error querying database.');

$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);


if ($row > 0) {

    while ($row = mysqli_fetch_array($result)) {
        $id = $row['id'];
        $title = $row['title'];
        $description = $row['description'];
        $pagebody = $row['pagebody'];
        $link = $row['link'];


        echo "<h2><a href='$link'>$title</a></h2></br>
        $description<br/><br/>";
    }
}   else 
echo "No results found for.\"<b>$keyword</b>\"";
?>

Any help would be much appreciated. I need to figure out how to make it so that if any of the keywords aren't recognized that it doesn't error out.


Solution

  • This won't fix the problems you have escaping your user input, but to answer your question in resolving the search error; your original code is keeping $i as equalling 0 through each iteration of the foreach loop so the query is coming out as:

    SELECT * FROM searchresults WHERE pagebody LIKE '%$each%' pagebody LIKE '%$each%' pagebody LIKE '%$each%'
    

    You need to modify the following lines:

    $query = "SELECT * FROM searchresults WHERE ";
    
    foreach ($terms as $each) {
    
        $i=0;
        if ($i == 0)
        $query .= "pagebody LIKE  '%$each%' ";
        else
        $query .= " OR pagebody LIKE  '%$each%' ";
    
    }
    

    change that to:

    $i=0;
    $query = "SELECT * FROM searchresults WHERE";
    
    foreach ($terms as $each) {
      if($i == 0){
        $query .= " pagebody LIKE '%$each%'";
      }else{
        $query .= " OR pagebody LIKE  '%$each%'";
      }
    $i++;
    }