php - 如何使用 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.';
}
?>
解决方案
循环时,您$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 { ... }
推荐阅读
- javascript - Typescript 无法从 EventEmitter 正确推断类型 T
RxJs 运算符中的参数(Angular 应用程序) - php - 使用一个控制器将数据添加到两个表
- dynamics-crm - OOTB 取消订单(Sales.SalesOrderRibbonActions.Instance.CloseOrder())函数失败
- python - s.bind((hostIPAddress,22)) OSError: 99
- reactjs - 如何在 React 应用程序中集成 keycloak 身份验证?
- swift - 如何使用 UIdocumentpickercontroller 导出 MP3 文档?
- microsoft-edge - 第一次取消时,window.Print() 函数在 Microsoft Edge 中不起作用
- sql-server - 在磁盘中,1 页只属于 1 个块?
- java - 从 Spring Boot 中读取文件夹会导致 FileNotFound 异常
- android - 如何监听属性更新状态 o android