MySQL在循环中搜索多个单词

时间:2013-05-08 14:07:39

标签: php mysql arrays

$keywords=array("test","tset");
$matches = implode(',', $keywords);
$sql = "SELECT * FROM `reg` WHERE title like in '%$matches%' group by p_title";

$data = mysql_query($sql); 
while($info=mysql_fetch_array($data))
{
Print " {$info['title']}<br /> ";
}

我想写一个像

这样的查询
   $sql = "SELECT * FROM `reg` WHERE title like in '%test%' group by p_title";
   $sql = "SELECT * FROM `reg` WHERE title like in '%tset%' group by p_title";

........

如何在一个查询中搜索每个关键字?

5 个答案:

答案 0 :(得分:1)

"SELECT * FROM reg WHERE title like in '%test%' or  title like in '%tset%' group by p_title"

答案 1 :(得分:0)

SELECT * FROM reg WHERE title like in '%{$keywords[0]}%' or title like in '%{$keywords[1]}%'

我建议使用循环。例如:

注意:这非常伪劣

$query = "SELECT * FROM reg WHERE title like in ";
foreach ($keyword in $keywords) {
  if (!$keyword is last)
    $query .= "'%$keyword%' or title like in ";
  else $query .= "'%$keyword%' group by p_title"
}

然后评估$query

答案 2 :(得分:0)

请参阅此帖子:MySQL LIKE IN()?

$keywords=array("test","tset");
$matches = implode('|', $keywords);
$sql = "SELECT * FROM `reg` WHERE title REGEXP '%$matches%' group by p_title";

$data = mysql_query($sql); 
while($info=mysql_fetch_array($data))
{
    Print " {$info['title']}<br /> ";
}

答案 3 :(得分:0)

$sql = "SELECT * FROM `reg` WHERE title ";

$where='';
foreach($keywords as $val)
{
  $where .= "LIKE '%$val%' OR title ";

}
$where = substr($where , 0, -9); // to remove last OR 
$finalSql = $sql .$where;

$data = mysql_query($finalSql); 

答案 4 :(得分:0)

implode PHP函数允许在没有循环的情况下实现它:

$keywords=array("test","tset");
$matches = implode("%' OR title LIKE '%", $keywords);
$sql = "SELECT * FROM `reg` WHERE title LIKE '%$matches%' group by p_title";

$data = mysql_query($sql); 
while($info=mysql_fetch_array($data))
{
Print " {$info['title']}<br /> ";
}