tags:

views:

52

answers:

1

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

            }
    }
}
A: 

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]);
}
manyxcxi
His query IS sorting by parent_id: ORDER BY parent_id ASC
Michael
Doh. Read it too fast. But you will still get parents followed by children. If you printed them out in order of retrieval the children wouldn't be printed with their associated parents.
manyxcxi