phpmysqlpdofetchall

How do you fetch all rows with pdo?


I am making a blog and I want to fetch all rows using a pdo statement but no matter what I do only one row comes back even though there are two rows in my database.

Here's the code sample where I connect:

<?php
try{
$link=new PDO('mysql:host=127.0.0.1;dbname=blog1','root','');
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);




 } catch(PDOException $e){
 echo $e->getMessage();
   die();
  }
?>

Then I try to fetch all rows

<?php
   require 'Escape.php';
  $posts_query=$link->query('SELECT * FROM posts');
  $posts_query->execute();
/* variable that holds a with the database link and query in it then fetches 
  all the data related to the query into and assoc array */
$result=$posts_query->fetchAll();

 //counting all rows
 $count=$posts_query->rowCount();
  if($count>0){



 foreach($result as $r){
      $id= $r['id'];
    $title= $r['title'] ;
   $content=$r['content'];
       $date= $r['date'];

//admin buttons
 $admin="";
//keeping title safe
    $Title=htmlentities($title);
    //keeping output safe
    $output=htmlentities($content);
 // styling the posts to be echoed with secure variables
$posts= "<div><h2><a href='view_post.php?pid=$id' class='names'>$Title</a> 
  </h2><h3>$date</h3><p>$output</p>$admin</div>";
  escape($posts);
   }
 echo"<div id=posts>$posts</div>";
  } else{
echo 'There are no posts to display.';
  }

    ?>

Solution

  • Your $posts's value is reset to the latest row when you loop, either you append the value of each post using concat . operator:

    if($count>0){
     $posts = "";
     foreach($result as $r){
        // Define your variable
        $posts .= "<div><h2><a href='view_post.php?pid=$id' class='names'>$title</a></h2><h3>$date</h3><p>$output</p>$admin</div>";
        escape($posts);
       }
      echo"<div id=posts>$posts</div>";
    } else { ... }
    

    Or printing each post while looping:

    if($count>0){
     $posts = "";
     echo "<div id='posts'>";
     foreach($result as $r){
        // Define your variable
        $posts = "<div><h2><a href='view_post.php?pid=$id' class='names'>$title</a></h2><h3>$date</h3><p>$output</p>$admin</div>";
        escape($posts);
        echo $posts;
       }
      echo"</div>";
    } else { ... }