php - 为什么php函数加载到错误的地方
问题描述
你好我的PHP代码有问题我有一个功能可以为我网站上的每个帖子获取评论该功能正在工作但数据位于错误的位置,如您在图片中看到的评论位于错误的位置和我需要将它们移动到图片中的位置
<?php
class posts{
static function getposts(){
$query = database::query("select * from posts join frinds on frinds.user1_id = posts.user_id or
frinds.user2_id= posts.user_id where frinds.user1_id = ? or frinds.user2_id =
?",array($_COOKIE['uid'],$_COOKIE['uid']));
if($query->rowCount() > 0){
$rows=$query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$id = $row['user_id'];
// if($id != $_COOKIE['uid']){
if($id != $_COOKIE['uid']){
$post_text = $row['text'];
$id= $row['id'];
echo posts::postbody($id,$post_text);
}
}
if($id == $_COOKIE['uid']){
$query = database::query("select * from posts where user_id = ?",array($_COOKIE['uid']));
if($query->rowCount() > 0){
$rows=$query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$post_text = $row['text'];
echo posts::postbody($row['id'],$post_text);
}
}
}
}
}
static function postbody($id,$post_text){
$body =" <div class='post'>
<div class='post_texts' ><p class='post_text'>$post_text</p>
</div>
<div class='comments'>
" .posts::comments($id)."
</div>
<form method='post'>
<input type='text' name='comment'>
<input type='submit' name='addcoment'>
</form>
</div> ";
return $body;
}
static function creatpost(){
$query = database::query("INSERT INTO `posts` (`user_id`, `text`) VALUES (?,
?);",array($_COOKIE['uid'],$_POST['text']));
}
static function comments($id){
$query = database::query("select * from comments join posts on comments.post_id = posts.id where
posts.id = ?",array($id));
if($query->rowCount() > 0){
$rows=$query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$comment = $row['comment'];
echo"<p>$comment</p>";
}
}
}
}
?>
解决方案
问题是您的静态方法调用posts::comments($id)
已经用于echo
输出注释。虽然帖子正文存储在$body
稍后才会回显的变量中。
您需要更改代码,以便在从数据库中收集评论时不会立即回显这些评论。但是它们要么放置在输出缓冲区中,要么返回到调用范围。这样它们就可以成为您尝试创建的实际帖子正文的一部分。
换句话说:当你打电话时,posts::comments($id)
你期望得到一些你试图连接到你的$body
变量的东西。但是您的方法永远不会返回任何东西。它只创建立即发送到客户端的输出。因此,它永远不会在您尝试收集帖子正文的地方获得该变量的一部分。
更新:
您如何“收集”评论以将它们全部返回?
static function comments($id){
$query = database::query("select * from comments join posts on comments.post_id = posts.id where
posts.id = ?",array($id));
if($query->rowCount() > 0) {
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
$comment = [];
foreach ($rows as $row) {
$comments[] = $row['comment'];
}
return implode("\n", $comments);
}
return "<p>No comments so far...</p>;
}
推荐阅读
- r - 为每个地址获取相同的坐标
- html - XSLT 对来自 2 个不同标签的数据进行分组并删除重复项
- python - 如何在 tensorflow 2.0 中创建训练、测试和验证拆分
- r - 来自同一变量的两个直方图的绘图比率
- ios - 在 xcconfig 文件中区分 iOS 和 macCatalyst
- ansible - Ansible 中的角色覆盖
- javascript - 从 TemplateRef 获取模板字符串
实例? - laravel - 发现意外数据。发现意外数据。Laravel 中的数据丢失
- javascript - 如果 HTML 表单未通过客户端验证,则阻止其发布
- python - 创建列表时的区别