conversion error from my_sql to PDO

-1

I modified my connection page with the MYSQL database for PDO but it is showing error, could anyone help me? There is a file that pulls the necessary information from the database to be sent to the index of my site and presents the last 5 comments in the database. It generates the following error:

Fatal error: Cannot use object of type PDOStatement as array in C:\xampp\htdocs\fraturaexposta.esy.es\home.php on line 87

In this case it would be in the line of the code down

  <div id="comenthome">" <?=$result['comentario']?> "<br>- <?=$result['user_name']?> .</div>

This is the file that connects to the database

<?php

define( 'MYSQL_HOST', 'localhost' );
define( 'MYSQL_USER', 'root' );
define( 'MYSQL_PASSWORD', '' );
define( 'MYSQL_DB_NAME', 'test' );

try
{
    $PDO = new PDO( 'mysql:host=' . MYSQL_HOST . ';dbname=' . MYSQL_DB_NAME, MYSQL_USER, MYSQL_PASSWORD );
}
catch ( PDOException $e )
{
    echo 'Erro ao conectar com o MySQL: ' . $e->getMessage();
}

$sql = "SELECT user_name, comentario FROM comentario ORDER BY coment_id desc limit 5";
$result = $PDO->query( $sql );
$rows = $result->fetchAll();


?>

This is the php that pulls the comments from the database to the page

<?php

    // se o número de resultados for maior que zero, mostra os dados

    if($rows > 0) {

        // inicia o loop que vai mostrar todos os dados

        do {

?>



<hr>

<div id="comenthome">" <?=$result['comentario']?> "<br>- <?=$result['user_name']?> .</div>



<?php

        // finaliza o loop que vai mostrar os dados

    }while ($rows = $PDO->fetch(PDO::FETCH_ASSOC));

    // fim do if 

}

?>
    
asked by anonymous 12.10.2016 / 18:40

1 answer

1

$rows = $result->fetchAll(); Returns an array, so just make a foreach with $rows .

The problem is your do-while that overwrites every time $rows

}while ($rows = $PDO->fetch(PDO::FETCH_ASSOC));

To fix do

<?php 
   // ...demais linhas
   $rows = $result->fetchAll();
?>

<?php foreach($rows as $result){?>
<hr>
<div id="comenthome">" <?=$result['comentario']?> "<br>- <?=$result['user_name']?>.</div>
<?php } ?>
    
13.10.2016 / 20:14