Search code examples
phpsearchsearch-engine

Php Search engine error


im trying to code a search engine.
It works apart from that if i enter a query like west coast, i also get the result of East coast. This happens because the keywords in east and west contain coast as a individual word.

However i want to seperate the two using this line of code:

<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM Search WHERE ";
foreach ($terms as $each){
    $i++;

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

}

If i echo that out the keywords using in the search form do get separated, but further on they don't
how can i fix this?

<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM Search WHERE ";
foreach ($terms as $each){
    $i++;

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

}
if($k == "" || $k == " ")
{
    echo "<p> Please enter a valid search term."; //If search is empty or contains only a space.
    exit;
}
//connect to database
mysql_connect("LOCALHOST" ,"ROOT" ,"PASSWORD");
mysql_select_db("DATABASE");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if($numrows > 0){
    while($row = mysql_fetch_assoc($query))
    {
        $id = $row['id'];
        $title = $row['title'];
        $description = $row['description'];
        $keywords = $row['keywords'];
        $link = $row['link'];
        echo "<h2><a href ='$link' class='searchcolor' color='#a8a8a8'> $title</a></h2>
            $description<br />
            This page contains information about \"<b>$query</b>\"<br /><hr>";
    }

}
else
    echo "No results for \"<b>$k</b>\"";

//disconnect
mysql_close();


?>

Solution

  • Your query:

    SELECT * FROM Search WHERE keywords LIKE '%west%' OR keywords LIKE '%$coast%';
    

    Will return results which match either of those keywords because of the OR. Use AND if you want the results to match all keywords.

    I.e. change

    $query .= "OR keywords LIKE '%$each%' ";
    

    To

     $query .= "AND keywords LIKE '%$each%' ";