你好,我的 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>;
}
关于php - 为什么 php 函数加载到错误的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67651752/