Force exact string MATCH for PDO prepared statements

喜欢而已 提交于 2020-07-03 10:04:49

问题


I have recently adopted PDO prepared statements. When writing WHERE MATCH clauses, I used to perform exact string MATCH as follows:

WHERE MATCH(some_column) AGAINST('\"$some_term\"')

It worked perfectly. Now I have switched to using PDO bindValue as follows:

WHERE MATCH(some_column) AGAINST(:some_term)

When binding a string with multiple words such as "orange bicycle", I get results for "orange" and "bicycle" whereas what I want is an exact match for "orange bicycle".

How do I force an exact string MATCH for my PDO prepared statements?

(I have Googled and searched on this site yet I cannot find any discussion of this question anywhere. I can't be the first person to ask this question but I cannot find the answer!)


回答1:


Make sure you are putting quotes around the variable specified in AGAINST.

In PHP:

$some_term = '"'.$some_term.'"'; // Adds quotes around string

$stmt = $db->prepare('SELECT * FROM example WHERE MATCH(some_column) AGAINST(:some_term)');
$stmt->bindParam(':some_term', $some_term, PDO::PARAM_STR);
$stmt->execute();

Or you could do it in the MySQL statement as well:

$stmt = $db->prepare('SELECT * FROM example WHERE MATCH(some_column) AGAINST(CONCAT(\'"\',:some_term,\'"\')');
$stmt->bindParam(':some_term', $some_term, PDO::PARAM_STR);
$stmt->execute();

According to the MySQL documentation on Boolean Full-Text Searches:

A phrase that is enclosed within double quote (“"”) characters matches only rows that contain the phrase literally, as it was typed. The full-text engine splits the phrase into words and performs a search in the FULLTEXT index for the words. Nonword characters need not be matched exactly: Phrase searching requires only that matches contain exactly the same words as the phrase and in the same order. For example, "test phrase" matches "test, phrase".

If the phrase contains no words that are in the index, the result is empty. For example, if all words are either stopwords or shorter than the minimum length of indexed words, the result is empty.



来源:https://stackoverflow.com/questions/27053879/force-exact-string-match-for-pdo-prepared-statements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!