首页 > 解决方案 > 如何使用 pdo 获取所有行?

问题描述

我正在制作一个博客,我想使用 pdo 语句获取所有行,但无论我做什么,即使我的数据库中有两行,我也只会返回一行。

这是我连接的代码示例:

<?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();
  }
?>

然后我尝试获取所有行

<?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.';
  }

    ?>

标签: phpmysqlpdofetchall

解决方案


循环时,您$posts的值将重置为最新行,或者使用 concat.运算符附加每个帖子的值:

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 { ... }

或在循环时打印每个帖子:

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 { ... }

推荐阅读