我做了一个PHP MySQL搜索,自定义可能是像word或word1 word2或word1 word2 word3这样的类型。我需要获得最终的查询,如下所示
$qry = "SELECT title,content,date
FROM articles WHERE
(title like '%$word1%' and title '%$word2%')
OR
(content like '%$word1%' and content title '%$word2%')"
OR
(title like '%$word1%' and content title '%$word2%')
OR
(title like '%$word2%' and content title '%$word1%'); // make sure custom type words all match in database column title and content, maybe only '%$word1%', or maybe multi words '%$word1%', '%$word2%', '%$word3%'...我使用了下面的一些代码,但它无法达到我的请求。如何让它变得正确?谢谢。
$qry = "SELECT title,content,date FROM articles";
if($_REQUEST['search']!=""){
$searchText = $_REQUEST['search'];
$words = preg_split("/\s+/",$searchText);
$uniqueWords = array_keys(array_flip($words));
$parts = '';
foreach($uniqueWords as $word){
$parts[] = " content like '%$word%' ";
}
$where = implode(" AND ", $parts);
foreach($uniqueWords as $word){
$parts[] = " title like '%$word%' ";
}
$where1 = implode(" AND ", $parts);
foreach($uniqueWords as $word){
$parts[] = " title like '%$word%' OR content like '%$word%' ";
}
$where2 = implode(" AND ", $parts);
$qry .=" WHERE $where OR $where1 OR $where2 Order By date DESC ";
}发布于 2011-04-07 17:42:00
我不确定您到底想要什么(您是想匹配标题或内容中的任何关键字,还是将两个关键字都匹配到两个列...)但是像这样的东西呢:
$keywords = explode(' ',mysql_real_escape_string($_REQUEST['search']));
$qry = "SELECT title,content,date FROM articles WHERE (";
$qry2 = '';
foreach($keywords as $n => $word)
{
$qry2 .= " title LIKE '%$word%' OR content LIKE '%$word%' OR";
}
$qry .= trim($qry2, 'OR');
$qry .= ") ORDER BY title";没有对此进行测试,但看起来还可以。
https://stackoverflow.com/questions/5578789
复制相似问题