关键字mysql搜索返回不准确的结果

I am using the code below to search my database based on keywords given by the user. It seems to work fine for the most part, but i am searching both based on location and keywords. This is where I have the issues.

If i put no location in and search it returns all results regardless of location, which is fine. If i put in a location that does not exist and some keywords, It returns all results matching the keywords and seems to ignore the location.

Also if i leave the keywords empty and search by a location that does exist, it seem that it ignores the location again and just returns all results.

So it would seem my logic for setting the location is not working.

$keys = explode(" ",$tag);

    $search_sql = "SELECT DISTINCT providers.* FROM providers JOIN provider_tags ON providers.id = provider_tags.provider_Id JOIN tags ON provider_tags.tag_id = tags.id WHERE tags.tag_name LIKE '%$tag%' OR providers.provider_name LIKE '%$tag%' OR providers.provider_contact_name LIKE '%$tag%' OR providers.provider_features LIKE '%$tag%' ";

    foreach($keys as $k){
        $search_sql .= " OR tags.tag_name LIKE '%$k%' OR providers.provider_name LIKE '%$k%' OR providers.provider_contact_name LIKE '%$k%' OR providers.provider_features LIKE '%$k%' ";
    }

    $search_sql .= " AND (providers.provider_town LIKE '%{$location}%' OR providers.provider_local_area LIKE '%{$location}%' OR providers.provider_postcode LIKE '%{$location}%')";

    echo $search_sql;
    $gettags = mysqli_query($con, $search_sql) or die(mysqli_error($con));

You are adding a bunch of OR conditions in a loop and then a big AND condition for the location. Your AND condition is checked with the last OR of the loop. If any of the others OR in the condition is true then you get a result no matters the AND condition.

Edit :

You'll probably get the results you want if you :

  • wrap every OR conditions with parenthesis;
  • wrap all the OR conditions together.

Something like :

$search_sql = "SELECT DISTINCT providers.* FROM providers JOIN provider_tags ON providers.id = provider_tags.provider_Id JOIN tags ON provider_tags.tag_id = tags.id WHERE ( (tags.tag_name LIKE '%$tag%' OR providers.provider_name LIKE '%$tag%' OR providers.provider_contact_name LIKE '%$tag%' OR providers.provider_features LIKE '%$tag%') ";

foreach($keys as $k){
    $search_sql .= " OR (tags.tag_name LIKE '%$k%' OR providers.provider_name LIKE '%$k%' OR providers.provider_contact_name LIKE '%$k%' OR providers.provider_features LIKE '%$k%') ";
}

$search_sql .= ") AND (providers.provider_town LIKE '%{$location}%' OR providers.provider_local_area LIKE '%{$location}%' OR providers.provider_postcode LIKE '%{$location}%')";