我需要做一个简单的查询
$array_of_ids = array();
//poulate $array_of_ids, they don't come from another db but from Facebook
//so i can't use a subquery for the IN clause
$wpdb->prepare("SELECT id from table where id IN (%d, %d)", $array_of_ids [0], $array_of_ids [1]);
问题是,如果我在数组中有 200 个元素,那么处理这个问题的正确方法是什么?我必须手动构建 200 %d
的查询吗?我需要这个查询,因为我必须将我的数据库与 facebook 数据"同步",并且我必须检查我在数据库中的用户是否存在,更新存在的用户,插入新用户并删除那些不是我的朋友的用户。
如果您确定数组元素是数字:
$wpdb->prepare("SELECT id FROM table WHERE id IN ("
. implode(',',$array_of_ids) . ")");
否则,您可以使用vsprintf
形式的prepare
传入参数数组:
$wpdb->prepare("SELECT id FROM table WHERE id IN ("
. str_repeat("%d,", count($array_of_ids)-1) . "%d)" , $array_of_ids);
我不确定这是否是一个好方法,但你可以用这种方式做到这一点:
$sql = "SELECT id from table where id IN ("
. implode(',', array_fill(0, count($array_of_ids), "%d"))
. ")";
call_user_func_array(array($wpdb, 'prepare'), $array_of_ids);
这将构建一个具有适当%d
数的字符串,然后使用 call_user_func_array
来动态地执行此操作。
也就是说,我不确定这是否真的是一个准备好的语句值得麻烦的情况,因为清理整数是多么容易。
是的,动态SQL是这里的方式。幸运的是,整数很容易不搞砸。
$vals = array_filter(array_map('intval', $vals));
确保至少有一个值,然后将其内爆。这里不需要准备好的语句,只需执行 sql。
由于这还没有被接受的答案,我将采用我的方法array_filter
$array_of_ids = array(0,1,1,2,3,5,8,13);
echo "SELECT id from table where id IN (".implode(',', array_filter($array_of_ids,'is_int')).")";
将输出
SELECT id from table where id IN (0,1,1,2,3,5,8,13)
而
$array_of_ids = array('zero',1,true,2,3,5,8,'thirteen');
echo "SELECT id from table where id IN (".implode(',', array_filter($array_of_ids,'is_int')).")";
将输出
SELECT id from table where id IN (1,2,3,5,8)
请注意,is_int
不适用于 $_GET 变量,因此请改用is_numeric
你可以
这样做:
$query = $wpdb->prepare("SELECT id from table where id IN :param");
$query->bindParam("param", "(".implode(',', array_map('intval', $array_of_ids)).")");