$ids = [3, 7, 9];
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("SELECT * FROM items WHERE id IN ($placeholders)");
$stmt->execute($ids);
$items = $stmt->fetchAll();
print_r($items);IN子句动态参数
这段代码用于通过PDO预处理语句安全地查询多个ID对应的数据,以下是逐步解析:
1. 动态生成占位符
$ids = [3, 7, 9];
$placeholders = implode(',', array_fill(0, count($ids), '?'));
array_fill(0, count($ids), '?')
生成与$ids数组长度相同的问号占位符数组,例如['?', '?', '?']。
implode(',', ...)
将问号数组拼接为字符串,结果为?,?,?。
作用:根据$ids的长度动态生成IN (?,?,?)子句,避免手动拼接SQL字符串的安全风险。
2. 准备SQL语句
$stmt = $pdo->prepare("SELECT * FROM items WHERE id IN ($placeholders)");生成的SQL模板为:
SELECT * FROM items WHERE id IN (?,?,?)
3. 绑定参数并执行
$stmt->execute($ids);
将
$ids数组的值按顺序绑定到占位符:?→3,?→7,?→9。实际执行的SQL等价于:
SELECT * FROM items WHERE id IN (3, 7, 9)
4. 获取结果
$items = $stmt->fetchAll(); print_r($items);
输出示例:
若数据库中存在ID为3、7、9的记录,输出类似:
Array ( [0] => Array ( [id] => 3 [name] => Item A ), [1] => Array ( [id] => 7 [name] => Item B ), [2] => Array ( [id] => 9 [name] => Item C ) )
关键优势
防SQL注入:参数通过预处理绑定,确保输入数据不会被解析为SQL代码。
动态适配:自动根据数组长度生成占位符,适合可变数量的查询条件。
代码简洁:避免手动拼接SQL字符串,减少错误风险。