Nökkvi Helgason Nökkvi Helgason - 7 months ago 305
SQL Question

PHP fatal error: Cannot use object of type PDOStatement as array

I am trying to make a comment page with this code but end up getting an error.

Here is the code:

$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/>' ;
}


And here is the error:


PHP Fatal error: Uncaught Error: Cannot use object of type PDOStatement as array in E:\utsdata\2T\2107982859\comment.php:61


Where line 61 is:
$id = $rows['id'];

Answer

1) Change

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

To

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

2) Change

 while($rows = ($getquery))

To

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

3) Add $getquery->execute();

Updated Code

$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/>' ;
}
Comments