I’m trying to make a commenting thread like Disqus has done. I’m having trouble setting up the logic in PHP to display the comments such that one can reply to each comment and those comments will then stay attached to each other.
here’s my MySQL comments table:
comment_id comment item_id replied_to_id time
1 hello1 1 1 1:00pm
2 hello2 1 1 2:00pm
3 hello3 1 3 3:00pm
4 hello4 2 4 4:00pm
5 hello5 1 2 2:00pm
6 hello6 1 3 6:00pm
item_id is a column which indicates the parent item that the comments are discussing.
If I pull from my database all the comments with item_id=1, then I’m not sure how to thread them such that the comment_id and replied_to_id‘s are appropriately matched. For example, comment_id=2 should be matched to comment_id=1.
Here’s my PHP:
<?foreach($comments as $row){
if($row->comment_id==$row->replied_to_id){
echo $row->comment."-".$row->time; //desired output: hello1-1:00pm
foreach($comments as $sub_row){
if($row->comment_id!=$sub_row->replied_to_id){
echo $sub_row->comment."-".$sub_row->time;// desired output: hello2-2:00pm
foreach($comments as $sub_sub_row){
if($row->comment_id!=$sub_sub_row->replied_to_id){
echo $sub_sub_row->comment."-".$sub_sub_row->time;// desired output: hello5-5:00pm
}
}
}
}
}
else{
echo $row->comment."-".$row->time; // desired output: hello3-3:00pm
}
}
This just looks wrong. There has got to be a better way to do this.
Simple demo, not necessarily the most optimal, but working:
This assumes top-level comments have no
replied_to_id(null). Your example with comment1replying to1doesn’t make much sense.