error in my_sql to PDO conversion

Asked

Viewed 69 times

-1

I modified my connection page with the MYSQL database to 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 present the last 5 comments present 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

which in this case would be in the code line below

  <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 

}

?>

1 answer

1


$rows = $result->fetchAll(); Already returns an array, so just do a foreach with $rows.

The problem is yours do-while that overwrites all the time $rows

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

To correct do:

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

<?php foreach($rows as $result){?>
<hr>
<div id="comenthome">" <?=$result['comentario']?> "<br>- <?=$result['user_name']?>.</div>
<?php } ?>
  • in case I would have to put the foreach on the website page or what connects with the database?

  • a ta understood now he subistitui o do-while

  • @Fracture exposed on the site page.

  • Thank you very much, it worked here

  • ♦ Could you take a look at my other PDO problem? http://answall.com/questions/163788/erro-em-contador-de-visitas-com-php-pdo-e-mysql

Browser other questions tagged

You are not signed in. Login or sign up in order to post.