php多个关键字搜索

时间:2015-03-10 22:07:15

标签: php mysql search

需要帮助我的php搜索多个关键字,下面的代码没有显示任何结果,但是当我删除explode函数和foreeach构造时,它可以工作,但只显示1个关键字的结果。

例如,我在列中有一个关键字列表: 苹果,红,蓝,书,黄鸟。

使用下面的代码,如果我在搜索框中输入红苹果,它将不会产生任何结果,我希望它显示包含我输入的关键字的所有结果。感谢

$search = $_POST['search'];
$search = strtoupper($search); 
$search = strip_tags($search); 
$search = trim ($search); 
$search = explode(",",$search);

$query=$db->prepare("SELECT * FROM thread WHERE title like '%".$search."%' OR keyword like '%".$search."%' OR description like '%".$search."%'");
foreach($search as $k)
{$query=$db->prepare("OR keyword LIKE '%$k%' OR title LIKE '%$k%' OR description LIKE '%$k%'");}
$query->execute(array('title' => $search, 'description'=>$search, 'keyword'=>$search));
$query->setFetchMode(PDO::FETCH_ASSOC); 

$List="";   

if($query->rowCount()<1)
    {$List.="<div class='containerr'>No results found.</div>";}
else
{

while($row=$query->fetch())
{
    $vid=$row['id'];
    $user=$row['username'];
    $preview=$row['preview'];
    $names=$row['names'];
    $good=$row['good'];
    $date=$row['date'];
    $date=date('M-d-Y', strtotime($date));
    $title=$row['title'];

$List.='<div class="LISTT"><a href="mp.php?id='.$vid.'">'.$preview.'<br/>
                        <label>'.$title.'</label><br/>
                        <label style="color:black;">Added:</label> <label style="color:#666666">'.$date.'</label></a></div>';
}

1 个答案:

答案 0 :(得分:0)

问题是,您覆盖SQL而不是附加到SQL。除此之外,你运行标题搜索冗余组合值,我想这不是你想要的。试试这个:

$search = $_POST['search'];
$search = strtoupper($search); 
$search = strip_tags($search); 
$search = explode(",",$search);

$sql=array("SELECT * FROM thread WHERE ");
foreach($search as $k) {
  $k=trim($k);
  $sql[]="keyword LIKE '%$k%' OR title LIKE '%$k%' OR description LIKE '%$k%'";
}
$sql=implode(' OR ', $sql);
$query=$db->prepare($sql);
$query->execute(array());
$query->setFetchMode(PDO::FETCH_ASSOC);