将可变数量的参数传递给Postgresql

时间:2013-03-27 04:53:04

标签: php postgresql pdo parameterized

如何将随机数量的参数传递给查询?以下代码块显示了尝试的内容。所有失败都显示为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;

2 个答案:

答案 0 :(得分:1)

尝试自己生成查询:

$values = array(1,2,3);
// Generate the query
$params = substr(str_repeat("?,", sizeof($values)), 0, -1);

$sql = "SELECT query FROM nc_reports WHERE id IN ($params)";

$sth = $dbh->prepare($sql);

for ($i = 0; $i < sizeof($values); $i++)
{
    $sth->bindValue($i+1, $values[$i], PDO::PARAM_INT);
}
$sth->execute();
// Iterate over the results
while (($result = $sth->fetch()) !== FALSE) {
    echo var_dump($result);
}
$dbh = null;

答案 1 :(得分:-2)

@FoolishSeth:谢谢你指点我的答案。由于代码格式化,我无法理解最初讨论的内容。我能够使它工作,但不使用任何(没有结果)或IN(只有第一个结果)。

执行和获取被移动到循环中,$ values数组中的每个项目都被单独查询并添加到$ results数组。

$values = array(1,2,3);

$sql = "SELECT column FROM table WHERE id = ?";

$sth = $dbh->prepare($sql);

$result = array();

foreach($values as $key => $val)
{
    $sth->bindValue(1, $val, PDO::PARAM_INT);
    $sth->execute();
    $result[$key] = $sth->fetch(PDO::FETCH_NUM);
}

echo var_dump($result);

上面根据需要返回了三行。我没有机会针对大的$ values []测试这个,但是对于预期的少量记录,这应该有效。