I have built a PHP comment system with all the necessary columns and can pull out the data just fine. However I want to make it have threaded replies (replies to comments). I added a field named parent_id so that if a reply to a comment is made, the parent_id field is set to the id of the parent comment. My question is how can I pull out the data for each comment but show the the nested replies? Is there a way to to get all the rows into an array that I can out put so that replies are nested? my current sql that works is: SELECT comments.comment, comments.projectid, comments.ownerid, comments.parent_id, users.userid , users.username, users.avatar FROM comments JOIN users ON comments.ownerid = users.userid WHERE comments.projectid = '$projid' ORDER BY id DESC LIMIT 10 Code (markup): i'm pulling it out with PHP like: while ($row = mysqli_fetch_array($query)){ $comment = $row['comment']; etc.... Which works but not for nesting the the children with the parent_id set. Can anyone show some code as to how I might achieve this ? Edit: I need to do this all in one query
Hey, maybe this will help... $sql = "SELECT comments.comment, comments.projectid, comments.ownerid, comments.id, users.userid , users.username, users.avatar FROM comments JOIN users ON comments.ownerid = users.userid WHERE comments.projectid = '$projid' ORDER BY id"; $query=mysql_query($sql); while ($row = mysqli_fetch_array($query)) { $comment = $row['comment']; $sql = "SELECT comments.comment, comments.projectid, comments.ownerid, users.userid , users.username, users.avatar FROM comments JOIN users ON comments.ownerid = users.userid WHERE comments.projectid = '$projid' AND comments.parent_id ='".$row['id']."' ORDER BY id"; $query2=mysql_query($sql); while ($row2 = mysqli_fetch_array($query2)) { ... ... ... PHP:
I suggest that you make another table named 'replies' with foreign key 'parent'. So you could for each comment print replies.
ker thanks for your help but I apologize for not being clear. I need to do this using only one query. The reason is because if a system with lots of comment has lots of replies then it would eventually bog the system down with tons of queries. Somehow I need to save the data in some arrays and then output it from them I think.