简体   繁体   中英

PHP/MySQL How to make my comments and replies display correctly?

I'm trying to display my comments and my comments replies on my web page but I can't get the replies to display with the correct comment can some one help correct this problem?

And by the way all the if else statements are to display different colors for the commenter or replier if he or she is the page creator or user.

Here is the MySQL tables.

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)
);

Here is the PHP & MySQL code.

$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>';

            }
    }
}

You could pull the comments into an associative array, determine if they are a parent, then attach children to the parent. After you have sorted/matched your comments, loop through again and spit them out.

Something very roughly like:

$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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM