dongwuxie5112 2014-08-14 07:54
浏览 651
已采纳

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 08: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条)
编辑
预览

报告相同问题?