'How to use MySQL MATCH AGAINST IN BOOLEAN MODE to return results for at least 1 matching keyword inside a keywords string?
I have this query for searching database entries based on keywords entered on a search box.
// function to get search keywords from url
$q = furl($_GET['q']);
$sExp = preg_split('/\s+/',$q);
$secure_keywords = array();
foreach ($sExp as $key=>$keyword){
if (strlen($keyword) >= 3){
// cut off words that are less than 3 chars
$secure_keywords[] = $keyword;
}
}
$kwords = count($secure_keywords);
foreach ($secure_keywords as $key=>$keyword)
{
// function to prevent sql injection
$keyword = sql_proof($keyword);
$query="SELECT * FROM listings WHERE MATCH (meta_keywords) AGAINST ('$keyword' IN BOOLEAN MODE) ORDER BY id";
}
When 2 or more words are used, if at least 1 word is misspelled then the query will not return any results (even if results do exist for the rest of the words in the keywords entered). For example, I enter the word "good" and I get at least 1 result, but if I use "good point" the query doesn't return any results, so it totally ignores the matching results for the word "good". Is there a way for the query to match results if there is at least 1 matching word in the keywords entered? Thanks
Solution 1:[1]
Instead of using 'In boolean mode' try
SELECT * FROM articles WHERE MATCH (title, body) AGAINST ('database test')
It returns result even if you have no word like 'test' after database
SELECT * FROM tablename WHERE MATCH (col1, col2) AGAINST ('string to be searched')
Solution 2:[2]
Check out the below solution for a way to match the results against ANY of the keywords used. Also check the docs for more info on operators and boolean fst http://dev.mysql.com/doc/refman/5.1/en/fulltext-boolean.html
// function to get search keywords from url
$q = furl($_GET['q']);
$sExp = preg_split('/\s+/',$q);
$secure_keywords = array();
foreach ($sExp as $key=>$keyword){
if (strlen($keyword) >= 3){
// cut off words that are less than 3 chars
$secure_keywords[] = $keyword;
}
}
$kwords = count($secure_keywords);
//init empty keywords array
$keywords = array();
//secure all keywords
$keywords = array_map(function($item){ return sql_proof($item); }, $secure_keywords);
//implode the words with a space between
$keywords = implode(" ",$keywords);
//just one query with match against ANY of the words from initial keyword array
$query="SELECT * FROM listings WHERE MATCH (meta_keywords) AGAINST ('$keywords' IN BOOLEAN MODE) ORDER BY id";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Deepika Janiyani |
| Solution 2 |
