为什么在发布多个回复时,Inner join语句会显示重复的注释

时间:2016-09-23 20:59:52

标签: php sql-server join mysqli while-loop

我有这个评论和回复系统 -

$sql = "SELECT comments.comment_id, comments.user, comments.comment, comments.date, 
comments.post_id, replies.reply, replies.username, replies.replyDate 
    FROM comments 
    LEFT JOIN replies ON comments.comment_id = replies.com_id WHERE comments.post_id=$id";

$result = $conn->query($sql);
if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

    $date = $row['date'];
    $mydate = date("M jS g:i a",strtotime($date));

    $rdate = $row['replyDate'];
    $newdate = date("M jS g:i a",strtotime($rdate));

    $user = $row['user'];
    $username = $row['username'];
    $comment = $row['comment'];
    $reply = $row['reply'];
    $comID = $row['comment_id'];
    $post_id= $row['post_id'];

    echo '<div id="comuser">'.$user.': </div>';
    echo '<div id="icomment">'.$comment.'</div>';
    echo '<div id="comdate">'.$mydate.'</div>';
    echo '<div class="replyBTN">reply</div>';
    echo '<form method="post" class="replyForm" action="get_reply.php?reply='.$comID.'&&title='.$title.'&&post='.$post_id.'">';
    echo '<input type="text" id="addReply" name="addReply" placeholder="add reply">';
    echo '</form>';
    echo '<div id="replyCont">';
    echo '<div id="replyUser">'.$username.'</div>';
    echo '<div id="replyDate">'.$newdate.'</div>';
    echo '<div id="reply">'.$reply.'</div>';
    echo '</div>';

}
} else {
echo "<div id='noCom'>no comments..</div>";
}

一切都很好,我加入了我的两张桌子,评论和回复..

但是当我在一条评论上留下2条回复时,它会复制评论以显示两条回复,而不是在一条相应的评论下发布两条回复。我的sql语句错了吗?

我根据评论ID加入2个表,评论ID是评论的主键,并在留下回复时插入回复表中。

enter image description here

由于

1 个答案:

答案 0 :(得分:1)

查询结果的每一行都包含来自commentsreplies表的信息。如果您不希望看到每个回复重复的注释信息,只需在while循环的第一次迭代中打印它。

$first = true;
while($row = $result->fetch_assoc()) {

    $date = $row['date'];
    $mydate = date("M jS g:i a",strtotime($date));

    $rdate = $row['replyDate'];
    $newdate = date("M jS g:i a",strtotime($rdate));

    $user = $row['user'];
    $username = $row['username'];
    $comment = $row['comment'];
    $reply = $row['reply'];
    $comID = $row['comment_id'];
    $post_id= $row['post_id'];

    if ($first) {
        echo '<div id="comuser">'.$user.': </div>';
        echo '<div id="icomment">'.$comment.'</div>';
        echo '<div id="comdate">'.$mydate.'</div>';
        echo '<div class="replyBTN">reply</div>';
        echo '<form method="post" class="replyForm" action="get_reply.php?reply='.$comID.'&&title='.$title.'&&post='.$post_id.'">';
        echo '<input type="text" id="addReply" name="addReply" placeholder="add reply">';
        echo '</form>';
        $first = false;
    }
    echo '<div id="replyCont">';
    echo '<div id="replyUser">'.$username.'</div>';
    echo '<div id="replyDate">'.$newdate.'</div>';
    echo '<div id="reply">'.$reply.'</div>';
    echo '</div>';

}

顺便说一下,您应该使用htmlentities($comment)htmlentities($reply)来防止跨站点脚本攻击。