如何在PHP中使用带有IN子句的查询中使用准备好的语句 [英] How to use prepared statements in queries with an IN clause in PHP

查看:337
本文介绍了如何在PHP中使用带有IN子句的查询中使用准备好的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做一个简单的查询

I need to make a simple query

$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数据,并且我必须检查数据库中存在的用户是否存在,更新存在的用户,插入新用户并删除不是我的朋友的用户./p>

The question is, if i have 200 elements in the array, what is the correct way to handle this?Do i have to manually build the query with 200 %d? I need this query because i must "sync" my database with facebook data and i have to check if the user i have in the db are present, update those that are present, insert new users and delete those that are not my friend.

推荐答案

如果可以肯定地知道数组元素是数字:

If you know for certain that the array elements are numeric:

$wpdb->prepare("SELECT id FROM table WHERE id IN ("
  . implode(',',$array_of_ids) . ")");

否则,您可以使用preparevsprintf形式来传递参数数组:

Otherwise, you can use the vsprintf form of prepare to pass in the array of parameters:

$wpdb->prepare("SELECT id FROM table WHERE id IN ("
  . str_repeat("%d,", count($array_of_ids)-1) . "%d)" , $array_of_ids);

这篇关于如何在PHP中使用带有IN子句的查询中使用准备好的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆