any-word search using LIKE %

Deadly 提交于 2019-12-12 03:11:45

问题


I have a database table which has a field firstname and a field lastname. I'm trying to implement an any-word search system using a search box where if let's say that we have a user named John Stanley Smith in the database (where firstname = John Stanley and lastname = Smith), I want to be able to return John Stanley Smith if the user types any of the following:

1- Any letter which is part of John Stanley Smith (j, s, l, e, y, m, etc...)
2- Any word which is part of John Stanley Smith
3- Any combination of words (in any order) which is part of John Stanley Smith, meaning that, if the user enters either John Stanley or John Smith or Stanley Smith or Stanley John (you get the idea) etc... I want to be able to find John Stanley Smith.

I know I can do this using the MySQL Fulltext Search feature, but if I do, point number one will not work (because the MySQL fulltext search feature only matches whole words, not substrings within a string). Also, there is a minimum number of words required for the search to be performed (set by the min_word_len constant). So, I really want to do this using LIKE %.

Thank you


回答1:


I might have misunderstood but have you considered just doing this:

SELECT * FROM customer WHERE
    CONCAT(firstname, " ", lastname) LIKE '%$pattern%'

if the user enters more than one word, separated by whitespaces, simple split the string into words and modify the query to

SELECT * FROM customer WHERE
    CONCAT(firstname, " ", lastname) LIKE '%$word1%'
 OR CONCAT(firstname, " ", lastname) LIKE '%$word2%'
 OR CONCAT(firstname, " ", lastname) LIKE '%$word3%'
 ...



回答2:


Hope this helps

$whereclauses=array();

$terms = explode(' ', $search_term);
foreach ($terms as $term) {
    $term = mysql_real_escape_string($term);
    $whereclauses[] = "CONCAT(first_name, ' ', last_name) LIKE '%$term%'";
}
$sql = "select * from table where";
$sql .= implode(' and ', $whereclauses);


来源:https://stackoverflow.com/questions/9406200/any-word-search-using-like

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