如何将评论发布到从数据库中提取的帖子并使用while循环显示

时间:2017-05-05 10:05:21

标签: php mysql

您好我正在尝试将类似论坛的功能纳入我的网站,用户可以发表评论,其他人可以回复每条评论。我从数据库中获取了帖子并通过条件while循环显示它们。问题是,每当我发布一个帖子的评论时,评论就会在数据库中输入,以显示所有评论。请帮助我如何改变这个问题。请注意,插入注释的php也在while()函数中,因为当我把它放在外面时,帖子的id没有得到并显示为零。

<?php
$sql="SELECT first_name,surname,post_id,post_body,post_date FROM  

users_posts INNER JOIN users ON users.user_id=users_posts.user_id     ORDER BY
post_date DESC LIMIT $start,$per_page";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_assoc($result)){
$post_date=$row["post_date"];
$post_id=$row["post_id"];
$post_date=$row["post_date"];
$first_name=$row["first_name"];
$surname=$row["surname"];
post_body=$row["post_body"];
?>
//html to display users posts goes here
<?php
if(isset($_POST['publishcomment'])){
$postcomment=mysqli_real_escape_string($conn,$_POST['postcomment']);
$date=date('Y-m-d H:i:s');
if(mysqli_query($conn, "INSERT INTO user_post_comments      (post_id,user_id,comment_date,comment_body) VALUES ('$post_id','$user_id','$date','$postcomment')")){
header("location:home.php");
}else{
$error="something went wrong";
}

}                    
}
}                         
?>     

1 个答案:

答案 0 :(得分:0)

评论会针对每条评论发布,因为您在while循环中有insert语句,而if(isset($_POST['publishcomment'])){将始终为true。

您应该在评论表单中添加隐藏字段和原始评论的post_id。

<input type="hidden" name="current_post_id" value="<?php echo $post_id; ?>">

然后将你的if语句更改为:

if ((isset($_POST['publishcomment'])) && ($_POST['current_post_id'] == $post_id)) {

然后,if语句只对用户评论的评论为真。

注意:我假设您要为此方案的每个注释字段创建单独的表单。否则,将始终提交隐藏字段,并且每个评论的if语句将再次为真。