您如何使用pdo获取所有行?

时间:2019-03-14 03:33:29

标签: php mysql pdo fetchall

我正在创建一个博客,我想使用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.';
  }

    ?>

2 个答案:

答案 0 :(得分:1)

循环时,您的$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 { ... }

答案 1 :(得分:0)

好像您在每次迭代中都重新分配帖子,尝试将值添加到数组中并在需要echo时将其内插。

  require 'Escape.php';
  $posts_query=$link->query('SELECT * FROM posts');
  $posts_query->execute();

  $result=$posts_query->fetchAll();

  $count=$posts_query->rowCount();
  if($count>0){
    $posts=[];
    foreach($result as $r){
      $id= $r['id'];
      $title= $r['title'] ;
      $content=$r['content'];
      $date= $r['date'];
      $admin="";
      $Title=htmlentities($title);
      $output=htmlentities($content);
      // Add the HTML to the $posts array, also taking advantage of NOWDOCS
      $posts[]= <<< HTML
<div>
  <h2>
    <a href='view_post.php?pid={$id}' class='names'>{$Title}</a> 
  </h2>
  <h3>{$date}</h3>
  <p>{$output}</p>
  {$admin}
</div>
HTML;
      escape($posts);
   }
   echo"<div id='posts'>" . implode('', $posts) . "</div>";
 } else {
   echo 'There are no posts to display.';
}

Here is a reference to PHP HEREDOCS.