問題描述
我有一個查詢表單的 select where like 查詢,如下所示:
I have a select where like query for a seach form which is as follows:
<?php
$bucketsearch = sanitizeone($_POST["bucketsearch"], "plain");
$bucketsearch = strip_word_html($bucketsearch);
?>
if(isset($_POST['search'])){
$result=MYSQL_QUERY( "SELECT * FROM buckets where bucketname like '%$bucketsearch%' order by bucketname");
}else{
$result=MYSQL_QUERY( "SELECT * FROM buckets order by bucketname");
}
我的問題是,如果有人搜索例如apple and pear",我沒有得到任何包含任何單詞的結(jié)果,我只能讓它返回包含所有單詞的結(jié)果(1 個結(jié)果).
My problem is that if someone searches for instance for "apple and pear" i do not get any results that contain any of the words, i can only make it return results (well 1 result) with all the words in it.
誰能幫我讓這個搜索更通用一些??提前致謝.
Can anyone help me make this search a bit more versitle?? Thanks in advance.
推薦答案
所以您想要使用輸入的每個詞進(jìn)行 AND 搜索,而不是使用確切的字符串?這樣的事情怎么樣:
So you want an AND search using each of the words entered, rather than the exact string? Howabout something like this:
$searchTerms = explode(' ', $bucketsearch);
$searchTermBits = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = "bucketname LIKE '%$term%'";
}
}
...
$result = mysql_query("SELECT * FROM buckets WHERE ".implode(' AND ', $searchTermBits).");
這會給你一個查詢:
SELECT * FROM buckets WHERE bucketname LIKE '%apple%' AND bucketname LIKE '%and%' AND bucketname LIKE '%pear%'
如果您想匹配任何搜索詞而不是全部,請將 AND 更改為 OR.進(jìn)一步的改進(jìn)可能涉及定義一些停用詞,例如和",以提供更好的結(jié)果.
change the AND to an OR if you want to match any of the search terms rather than all. Further improvements could involve defining some stop words like 'and' to give better results.
這篇關(guān)于PHP SQL SELECT where like search item with multiple words的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!