使用PDO回显显示表中的所有行

Mic*_*l N 5 php pdo

我正在尝试使用PDO回显表的所有行,但遇到了麻烦.

以旧的方式做我喜欢做的

$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)){
   $title= $row['title'];
   $body= $row['body'];
}
Run Code Online (Sandbox Code Playgroud)

但是我正在尝试使用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;
Run Code Online (Sandbox Code Playgroud)

哪个一直给我调用未定义的方法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);
?>
Run Code Online (Sandbox Code Playgroud)

工作,但我不认为我可以控制单个列,就像我用$ row = ['blah']; 我呢?它也像这样打印出来; 相当难看:

数组([0] =>数组([title] =>这是在数据库[0]中输入的测试标题

要正确使用PDO来做这件事需要做些什么?

Gre*_*ack 9

更改:

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

至:

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