如何将随机数量的参数传递给查询?下面的代码块显示了尝试的内容。所有失败都显示为 bool(false)。为了测试,使用三个整数来表示 id。
来自项目 1 的查询在 pgAdminIII 中手动执行,并且成功。对第 2 项和第 4 项的查询进行了回显和比较。它们看起来像预期的那样接近,但参数不具有约束力。
SELECT column FROM table WHERE id = ANY('{1,2,3}'::int[]);
SELECT column FROM table WHERE id = ANY('{?,?,?}'::int[])
1)这行得通。希望任何子句将是 1-N 个数字:
$sql = "SELECT column FROM table WHERE id = ANY('{1,2,3}'::int[])";
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_NUM);
echo var_dump($result);
$dbh = null;
2)这失败了:
$values = array(1,2,3);
$placeHolders = implode(',', array_fill(0, count($values), '?'));
$sql = sprintf("SELECT column FROM table WHERE id = ANY('{%s}'::int[])", $placeHolders);
$sth = $dbh->prepare($sql);
$sth->execute($values);
$result = $sth->fetch();
echo var_dump($result);
$dbh = null;
3)这失败了:
$values = array(':qwer' => 1, ':asdf' => 2, ':zxcv' => 3);
$sql = "SELECT colum FROM table WHERE id = ANY(\'{ :qwer , :asdf , :zxcv }\'::int[])"; //Below error caused if single quote not escaped.
$sth = $dbh->prepare($sql);
$sth->execute($values); // Invalid parameter number: :qwer if single quotes not escaped.
$result = $sth->fetch();
echo var_dump($result);
$dbh = null;
4)这失败(显式绑定参数):
$values = array(1,2,3);
$placeHolders = implode(',', array_fill(0, count($values), '?'));
$sql = sprintf("SELECT query FROM nc_reports WHERE id = ANY('{%s}'::int[])", $placeHolders);
$sth = $dbh->prepare($sql);
$i = 1;
foreach($values as $val)
{
//$sth->bindParam($i, $val, PDO::PARAM_INT);
$sth->bindValue($i, $val, PDO::PARAM_INT);
$i++;
}
$sth->execute();
$result = $sth->fetch();
echo var_dump($result);
$dbh = null;