6

PDO を使用してテーブルのすべての行をエコーアウトしようとしていますが、問題が発生しています。

古いやり方で、私はそれをしただろう

$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)){
   $title= $row['title'];
   $body= $row['body'];
}

しかし、私は PDO を試しています。

$result = $db->prepare("SELECT title, body FROM post");
$result->execute();

while ($row = $db->fetchAll(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}

echo $title;
echo $body;

Call to undefined method PDO::fetchAll() を与え続けます

マニュアルに記載されている例を実行する

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

動作しますが、 $row=['blah']; のように個々の列を制御できるとは思いません。私は?また、このように出力されます。かなり醜い:

Array ( [0] => Array ( [title] => これはデータベースに入力されたテストタイトルです[0]

これを行うために PDO を適切に使用するには、何をする必要がありますか?

4

2 に答える 2

9

変化する:

while ($row = $db->fetchAll(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}

に:

while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
于 2013-01-23T23:47:36.293 に答える
2

Call to undefined method PDO::fetchAll() を与え続けます

これにより、間違ったオブジェクトを使用しているというヒントが得られるはずです。2番目の例でわかるように、または while ループPDOStatement::fetchで使用する場合は、 PDOStatement::fetchAllです。

while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
    $title = $row['title'];
    $body = $row['body'];
}

その他の注意事項:

  1. $result行からわかるように、誤解を招く変数名です$result->execute()結果を実行するのではなく、ステートメントを実行します。$stmtこれが、マニュアルでor $sth(ステートメントハンドルだと思います) が使用されている理由です。
  2. echo行はwhileループ内にある必要があります。そうしないと、何度も何度も上書きしてから、最後の行のみを出力します。
于 2013-01-23T23:48:29.770 に答える