我在php上有一个数组,其中包含我想要检索的记录的一些ID,我用循环执行该操作,多次执行查询以获取所有这些ID。
foreach ($receivers as $id) {
$sth = $this->db->prepare("SELECT phone FROM contact WHERE idcontact = ?");
$sth->execute(array($id));
$res= $sth->fetch();
echo $res['phone'] ;
}
如何在单个查询中执行此操作,以便我不会在数百个查询中打扰数据库?
答案 0 :(得分:3)
$sth = $this->db->prepare("SELECT phone FROM contact WHERE idcontact IN (" . implode(",",$receivers) . ")");
来源:http://www.w3resource.com/mysql/comparision-functions-and-operators/in-function.php
更好的来源:http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html
答案 1 :(得分:3)
您可以将IN()
谓词与查询参数一起使用:
$placeholders = implode(",", array_fill(1, count($receivers), "?"));
$sth = $this->db->prepare("SELECT phone FROM contact WHERE idcontact IN ($placeholders)");
$sth->execute($receivers);