Force exact string MATCH for PDO prepared statements

前端 未结 1 1990
一向
一向 2021-01-25 07:38

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) AGAI         


        
相关标签:
1条回答
  • 2021-01-25 08:25

    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.

    0 讨论(0)
提交回复
热议问题