douliangbian7323 2012-02-24 16:34
浏览 47
已采纳

从数组OR逗号分隔的字符串:只在一个查询中从db获取字段

I have multiple numeric values which I can express as either an array, or as a comma-separated string. For each of these values I would like to select the corresponding database row. Is it possible to do this in one query?

// data examples
$array = array(3, 6, 200); // or more values
$string = '3,6,200' ; // or more values

I can do the following query for each value, to get a field from the table:

SELECT email FROM table WHERE id='$array_value';

But how can I get this in one query?

  • 写回答

3条回答 默认 最新

  • dongxu8533486 2012-02-24 16:40
    关注

    You should use IN operator. If $data is either array or comma separated list of numbers (string), do:

    $in = is_array($data) ? implode(',', $data) : $data;
    $query = "SELECT email FROM table WHERE id IN (" . $in . ")";
    

    Only do this if you are sure that elements in the array are safe.

    If you have to make your data safe you can do this

    $in = is_array($data) ? 
            "'" . implode("','", array_map('mysql_real_escape_string', $data)) . "'" : 
            "'" . mysql_real_escape_string($data) . "'";
    

    Or if you are expecting integer values, just go with:

    $in = is_array($data) ? 
            implode(',', array_map('intval', $data)) : 
            (int)$data;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记