0

由于某种原因,这段代码不起作用,我不知道为什么:

$action = array('id', 'lurl', 'account');
$request = 3;
$stm = $pdo->prepare("SELECT ? FROM (SELECT * FROM urls ORDER BY id DESC LIMIT ?) sub ORDER BY id ASC");
$stm->bindValue(1, implode(',', $action));
$stm->bindValue(2, $request, PDO::PARAM_INT);
$stm->execute();
$data = $stm->fetchAll();

它所做的只是返回以下数组:

Array ( [0] => Array ( [id,lurl,account] => id,lurl,account ) [1] => Array ( [id,lurl,account] => id,lurl,account ) [2] => Array ( [id,lurl,account] => id,lurl,account ) )

但是当我像这样在查询中手动输入数据时:

SELECT id,lurl,account FROM (SELECT * FROM urls ORDER BY id DESC LIMIT 3);

它做它应该做的事情。有人知道为什么吗?

4

2 回答 2

0

使用 bindValue 您只能绑定“值”而不是引用。要绑定引用,您需要使用 bindParam

改变:

$stm->bindValue(1, implode(',', $action));
$stm->bindValue(2, $request, PDO::PARAM_INT);

至:

$stm->bindParam(1, implode(',', $action));
$stm->bindParam(2, $request, PDO::PARAM_INT);
于 2013-05-18T19:02:14.250 回答
0

我猜想内爆的字符串会被引用,这是主要问题。您可以通过以下方式解决问题:

    $actions = array('id', 'lurl', 'account');

    $fields = implode(',', array_fill(0, count($actions), '?'));

    $request = 3;

    $stm = $pdo->prepare("SELECT " . $fields . " FROM (SELECT * FROM urls ORDER BY id DESC LIMIT ?) sub ORDER BY id ASC");

    foreach ($actions as $key => $action)
        $stm->bindValue(($key+1), $action);

    $stm->bindValue(2, $request, PDO::PARAM_INT);
    $stm->execute();

    $data = $stm->fetchAll();
于 2013-05-19T04:18:21.700 回答