在尝试了几个小时将全文索引添加到我的表中后,我发现Like%searchword%的工作原理也太像了。我从第一个查询中得到数组$keywordse
,然后用$keywordsonetoeight = implode(', ', $keywordse[0]);
创建一个逗号分隔的列表,输出为:string(25) "firstword, secondword, , , , , ,"
。我使用mysql,该表使用MyIsam运行。
$keywordse
看起来像这样:
array(1) { [0]=> array(8) { ["keyword1"]=> string(0) "" ["keyword2"]=>
string(5) "ballo" ["keyword3"]=> string(5) "ballo" ["keyword4"]=>
string(0) "" ["keyword5"]=> string(0) "" ["keyword6"]=>
string(0) "" ["keyword7"]=> string(0) "" ["keyword8"]=> string(0) "" } }
我的查询:
"SELECT *
FROM posts
WHERE title, text, area, contact LIKE %'$keywordsonetoeight'% AND (autorid != $userid)
ORDER BY id DESC";
输出为NULL
这项工作:
"SELECT *
FROM posts
WHERE title LIKE '%firstword%' AND (autorid != $userid)
ORDER BY id DESC";
不要直接在数组中使用implode()
函数,因为数组中确实存在几个空元素。首先从$keywordse[0]
数组中取消设置空数组元素,然后使用REGEXP
进行搜索。
你的代码应该是这样的:
foreach($keywordse[0] as $key => $value){
if(empty(trim($value))){
unset($keywordse[0][$key]);
}
}
$conditions = implode("|", $keywordse[0]);
$query = "SELECT *
FROM posts
WHERE (title REGEXP '{$conditions}'
OR text REGEXP '{$conditions}'
OR contact REGEXP '{$conditions}')
AND autorid <> {$userid}
ORDER BY id DESC";
// Now execute this $query
以下是参考资料:
- 正则表达式
如果您想比较数组中的所有值,您可以使用REGEXP:
"SELECT *
FROM posts
WHERE title REGEXP '$first_word|$second_word|$third_word'
OR text REGEXP '$first_word|$second_word|$third_word' ) AND (autorid != $userid)
ORDER BY id DESC";