我有1个名为 colors 的mysql表,行 id 和名称
1 - yellow 2 - black 3 - red 4 - green 5 - white 6 - blue
如果我有搜索字符串
,我怎样才能获得ID数组["colors"]=> string(14) "blue,red,white"
答案 0 :(得分:3)
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
select id from tab where find_in_set(name, '$colors') > 0
注意:根据Dan的评论,此查询不使用索引,并且在大型表上会很慢。使用IN的查询更好:
select id from tab where name IN ('blue', 'red', 'white')
答案 1 :(得分:2)
$array = explode(",", $colors);
$search = implode("', '", $array); // implode instead of impode
$sql = "
SELECT
id,
name
FROM
colors
WHERE
name IN ('$search')
";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
//do something with the matches
}
答案 2 :(得分:-2)
试试这个
$colors = "blue,red,white";
// Exploding string to array
$colors = explode($colors, ',');
$colors_list = array();
foreach($colors as &$color)
{
// Escaping every element
$colors_list[] = "'".mysql_real_escape_string($color)."'";
}
// Executing the query
$query = mysql_query('SELECT `id` FROM `colors` WHERE `name` IN ('.implode(', ', $colors_list).')');