将逗号分隔的id列表绑定到我准备好的语句时,我只返回一行,而我预计会有3行。
<?php
$dbh = new PDO("mysql:host=127.0.0.1;dbname=database", "user", "password");
$stmt = $dbh->prepare('SELECT * FROM Person WHERE PersonID IN (:p)');
$stmt->bindValue(":p", "3,4,5");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<pre>
<?php print_r($result); ?>
</pre>
如果我将stmt更改为
SELECT * FROM Person WHERE PersonID IN (3,4,5)
我按预期回来了3行,我很困惑!
答案 0 :(得分:3)
因为bind基本上将它包装在引号中并将其视为单个值。然后MySQL将其转换回整数,因此它仍然找到第一项的匹配。
你需要做IN(:p1,:p2,:p3)并分别绑定值
答案 1 :(得分:2)
这应该有效,它会动态构建您应该在语句中使用的占位符:
$idList = array(3, 4, 5);
$argList = join(',', array_fill(0, count($idList), '?'));
$stmt = $dbh->prepare("SELECT * FROM Person WHERE PersonID IN ($argList)");
$stmt->execute($idList);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);