繁体   English   中英

在PHP中使用LIKE构建MySQL搜索查询

[英]Building MySQL searching query using LIKE in PHP

我做了一个PHP MySQL搜索,自定义可能是类似wordword1 word2word1 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 ";
}

我不确定你究竟是在追求什么(你想要匹配标题或内容中的任何关键词,或者将两个关键词都匹配到两列......?)但是这样的事情怎么样:

$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";

没试过这个,但似乎没问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM