So let me give you some information, i have a blog system which is backed to a database, the database holds the title of the articles. Now i have tried to create a "related news" feature, and it is rather basic, it just takes the title of the existing page and splits it up like so (Note that $row_object_title is just the title pulled from the database):
$row_object_title_lower = strtolower($row_object_title);
$keywords = explode(" ",$row_object_title_lower);
I then run it through my function:
exclude_conjuctions($keywords);
code for that function(looks for certain words and removes it from the array:
function exclude_conjuctions($array){
global $keywords_new;
$keywords_new = $array;
$conjuctions = array("here","to","and","but","or","nor","for");
$counter = count($keywords_new);
foreach($conjuctions as $conjuction){
for($i=0;$i <= $counter;$i++){
if ($keywords_new[$i] == $conjuction){
unset($keywords_new[$i]);
}
}
}
return $keywords_new;
}
So now i will build my query to retreive all articles that have the keywords in the title:
$sql = '';
foreach ($keywords_new AS $keyword)
{
if ($sql != '')
$sql .= ' OR ';
$sql .= "object_title LIKE '%$keyword%'";
}
$squery = 'SELECT object_title FROM example_table WHERE '.$sql;
NOW. It seems to be working okay, but there are times when it returns a title which does not have the same words as the current article, so i investigated it and it seems it picks up parts of the word and returns it, which is of course not what we want, if you are confused take a look at this image:
Note how i search for "dow" and those letters are found in both the current title and the retrieved titles. Of course i need it to only return related articles that have the full words in the title, not part of the words. What am i doing wrong guys? maybe my MySQL query needs to be changed? maybe there is a better solution? would love some help.
This is a problem as you can imagine.
Thanks for the help in advance.
Try doing LIKE '% {$keyword} %'
Also your query is vulnerable for SQL Injections.
How can I prevent SQL injection in PHP?
EDIT : A better way to do this would be using a Regular Expression:
REGEXP '[[:<:]]{$keyword}[[:>:]]'
Instead of LIKE...