开发者

Mysql search with comma delimited string

I have 1 mysql table called colors with rows id and name

1 - yellow
2 - black
3 - red
开发者_Python百科4 - green
5 - white
6 - blue

How can I get array of IDs if I have, for example, search string

["colors"]=> string(14) "blue,red,white"


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

NB: as per Dan's comment below, this query doesn't use indexes and will be slow on a large table. A query with IN is better:

select id from tab where name IN ('blue', 'red', 'white')


$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
}


Try this

$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).')');

http://php.net/manual/en/function.explode.php

http://php.net/manual/en/function.implode.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜