Home » Php » php – mysql match against ~ example

php – mysql match against ~ example

Posted by: admin July 12, 2020 Leave a comment

Questions:

Below is an example sql I am stuck with, it will not return a hotel named “mill hotel”
It returns 10 other hotels. Any help would be great thanks


SELECT * FROM tbl WHERE match(hotel) against('the mill hotel' IN BOOLEAN MODE) LIMIT 10";

How to&Answers:

You need to specify the operators, because not specifying any results in an OR operation. Try this:

SELECT * FROM tbl WHERE match(hotel) against('+the mill hotel' IN BOOLEAN MODE) LIMIT 10";

Read more

Answer:

You can always use quotes to match the phrase mill hotel rather than the words mill and/or hotel:

SELECT * FROM tbl WHERE match(hotel) against('"the mill hotel"' IN BOOLEAN MODE) LIMIT 10;

or, simply:

SELECT * FROM tbl WHERE match(hotel) against('"mill hotel"' IN BOOLEAN MODE) LIMIT 10;

I believe that all

SELECT * FROM tbl WHERE match(hotel) against('+the mill hotel' IN BOOLEAN MODE) LIMIT 10;

does is require the word the to match, leaving mill and hotel as optional: if you want to require the whole phrase, it needs to be in quotes:

SELECT * FROM tbl WHERE match(hotel) against('+"the mill hotel"' IN BOOLEAN MODE) LIMIT 10;

although when you’ve only got one search phrase, as in this example, the plus sign is redundant.

Answer:

Use + (plus) in such case…

SELECT * FROM tbl WHERE match(hotel) against ('+the mill hotel' IN BOOLEAN MODE) LIMIT 10";

Read this for detailed information.

Answer:

12.9.2 Boolean Full-Text Searches

MySQL can perform boolean full-text searches using the IN BOOLEAN MODE modifier.

Boolean full-text searches have these characteristics:

  • They do not automatically sort rows in order of decreasing relevance.

12.9.1 Natural Language Full-Text Searches

By default or with the IN NATURAL LANGUAGE MODE modifier, the MATCH() function performs a natural language search for a string against a text collection. A collection is a set of one or more columns included in a FULLTEXT index. The search string is given as the argument to AGAINST(). For each row in the table, MATCH() returns a relevance value; that is, a similarity measure between the search string and the text in that row in the columns named in the MATCH() list.

So, you need to sort them or remove the limit on your results.

Answer:

To execute the following mysql query based on a phrase in PHP

SELECT * 
FROM tbl 
WHERE match(hotel) against('"the mill hotel"' IN BOOLEAN MODE)

You have to do like this:

$phrase = "the mill hotel";
$phrase= '"'.$phrase.'"'; // Adds quotes around string

$stmt = $db->prepare('SELECT * FROM tbl WHERE MATCH(hotel)    AGAINST(:phrase )');
$stmt->bindParam(':phrase ', $phrase , PDO::PARAM_STR);
$stmt->execute();

Thank you to @ub3rst4r for his answer: Force exact string MATCH for PDO prepared statements