PHP / MySQL如何正确显示我的评论和回复?

时间:2010-06-04 15:42:53

标签: php mysql

我正在尝试在我的网页上显示我的评论和评论回复,但我无法通过正确的评论显示回复,有人可以帮助纠正这个问题吗?

顺便说一下,如果评论者或回复者是页面创建者或用户,所有if else语句都会显示不同的颜色。

这是MySQL表。

CREATE TABLE comments (
comment_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INT UNSIGNED NOT NULL,
user_id INT UNSIGNED NOT NULL,
page_id INT UNSIGNED NOT NULL,
comment TEXT NOT NULL,
date_created DATETIME NOT NULL,
PRIMARY KEY (id),
KEY user_id (user_id),
KEY page_id (page_id)
);


CREATE TABLE users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL, 
PRIMARY KEY (id)
);

这是PHP& MySQL代码。

$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT comments.*, users.*
                             FROM comments
                             LEFT JOIN users 
                             ON comments.user_id = users.user_id
                             WHERE page_id = $page_id
                             ORDER BY parent_id ASC");

if (!$dbc) {
    print mysqli_error();
}  else {
    while($row = mysqli_fetch_array($dbc)){
        $comment_user = $row['user_id'];
        $comment_id = $row['comment_id'];
        $comments = $row['comment'];
        $parent_id = $row['parent_id'];

            if($comment_user == $user_id && $parent_id == 0){

                echo '<p class="page-creator-comment">' . $comments . '</p>';

            } else if($comment_user != $user_id && $parent_id == 0) {

                echo '<p class="commenter">' . $comments . '';

            } else if($comment_user == $user_id && $parent_id >= 1){

                echo '<p class="page-creator-reply">' . $comments . '</p>';

            } else if($parent_id >= 1){

                echo '<p class="reply">' . $comments . '</p>';

            }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以将注释拉入关联数组,确定它们是否是父项,然后将子项附加到父项。在对评论进行排序/匹配之后,再次循环并将它们吐出来。

非常类似于:

$comments = array();
if($parent_id == 0)
{
  $comments[] = array($comment_id => [all your comment data (possibly as stdObject)],array());
}
else if($parent_id  > 0)
{
  $comments[$parent_id][] => array($comment_id => [all your comment data]);
}