PHP致命错误:不能使用PDOStatement类型的对象作为数组

时间:2016-05-04 17:53:43

标签: php html mysql pdo

我正在尝试使用此代码制作评论页,但最终会收到错误。

以下是代码:

 $query = ("SELECT * FROM comment ORDER BY id DESC");

    $getquery = $connection->query($query);

    while($rows = ($getquery))
    {

        $id = $rows['id'];
        $names = $rows['name'];
        $comment = $rows['comment'];

        echo $name . '<br/>' . $comment . '<br/>' . '<br/>' ;
    }

这是错误:

  

PHP致命错误:未捕获错误:无法在E:\ utsdata \ 2T \ 2107982859 \ comment.php:61

中使用PDOStatement类型的对象作为数组

第61行是:$id = $rows['id'];

1 个答案:

答案 0 :(得分:3)

1)改变

$getquery = $connection->query($query);

$getquery = $connection->prepare($query);

2)改变

 while($rows = ($getquery))

while ($rows = $getquery->fetch(PDO::FETCH_BOTH)) {

3)添加$getquery->execute();

更新代码

$query = ("SELECT * FROM comment ORDER BY id DESC");

$getquery = $connection->prepare($query);
$getquery->execute();
while($result = $getquery->fetch(PDO::FETCH_BOTH);)
{

    $id = $rows['id'];
    $names = $rows['name'];
    $comment = $rows['comment'];

    echo $name . '<br/>' . $comment . '<br/>' . '<br/>' ;
}