我正在写博客,我想使用 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.';
}
?>
最佳答案
当你循环时,你的 $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 { ... }
关于php - 你如何使用 pdo 获取所有行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55154568/