dongwuxie5112 2014-08-14 15:54
浏览 648
已采纳

IN和WHERE,将变量作为字符串或数组传递[关闭]

I have a query that has a where condition, sometimes the condition can be a string and sometimes it can be an array. If it is an array I need to use IN.

The condition is passed in as a var.

What would be the best solution:

  1. Check if the passed in var is an array - if not then put it in an array. Then always run an IN search.

  2. Change the SQL that is ran, so if its an array, run an IN search, if not doing a WHERE.

  • 写回答

3条回答 默认 最新

  • dqs86517 2014-08-14 16:03
    关注
    $var = array('test');
    $sql = "SELECT * FROM `table` WHERE `id` " ? is_array($var) ? "IN (" . implode(',',$var) . ")" : " = " . $var;
    

    or just do:

    $var = array('test');
    if(!is_array($var)){
        $var = array($var);
    }
    $sql = "SELECT * FROM `table` WHERE `id` IN (" . implode(',',$var) . ")";
    

    whichever you prefer. In terms of performance, I'd go with the first one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?