我进行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 ";
}
答案 0 :(得分:2)
我不确定你究竟是在追求什么(你想要匹配标题或内容中的任何关键词,还是将两个关键词都匹配到两列......?)但是这样的事情呢?
$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";
未对此进行测试,但似乎没问题。