Mysql search with comma delimited string

前端 未结 3 554
花落未央
花落未央 2020-12-21 19:56

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

1 - yellow
2 - black
3 - red
4 - green
5 - white
6 - bl         


        
相关标签:
3条回答
  • 2020-12-21 20:27
    $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
    }
    
    0 讨论(0)
  • 2020-12-21 20:34

    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')
    
    0 讨论(0)
  • 2020-12-21 20:37

    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 讨论(0)
提交回复
热议问题