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

内破された文字列が引用されると思いますが、これが主な問題です。次の方法で問題を解決できます。

    $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 に答える