mysql - 和,喜欢和/或组合

时间:2018-04-14 10:10:47

标签: php mysql

我需要这样的东西:

$tags = array('sky', 'earth', 'blue', 'green');  // this varies each time

$st = $db->query("
select id from images where width > 960
and height > 540
and tags like '%" . any of $tags element . "%'");

问题是最后一行 - 怎么说呢 有什么帮助吗?

3 个答案:

答案 0 :(得分:0)

添加:

AND tags IN implode('","', $tags)

而不是像

这将使$ tags数组字符串并在其间放置一个komma。

结果是:

$st = $db->query('
select id from images where width > 960
and height > 540
and tags IN ("' . implode('","', $tags) . '")';

答案 1 :(得分:0)

试试这个,

$tags = array('sky', 'earth', 'blue', 'green');  // this varies each time

$sql = []; // Stop errors when $words is empty

foreach ($tags as $tag => $value) { 
   $sql[] = 'tags LIKE "%' . $value . '%"';
}

//create SQL string
$sql = 'select id from images where width > 960 and height > 540 and ' .implode(" OR ", $sql);

$st = $db->query($sql);

答案 2 :(得分:-1)

$tags = array('sky', 'earth', 'blue', 'green');  // this varies each time
$tag_str="";
foreach($tags as $tag){
$tag_str.=" tags like '%" . $tag . "%' OR ";
}
$tag_str=rtrim($tag_str,"OR ");
$st = $db->query("
select id from images where width > 960
and height > 540
and (".$tag_str.")");