PHP MySQL如何检索在单个查询中匹配多个不同值的记录

时间:2014-06-25 00:25:36

标签: php mysql sql query-optimization

我在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'] ;
            }

如何在单个查询中执行此操作,以便我不会在数百个查询中打扰数据库?

2 个答案:

答案 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);