[eluser]deczo[/eluser]
For 2 levels only the easiest way will be just to select comments and order them properly, then output them with right class.
Let's say we have such table:
Code:
mysql> select * from comments;
+----+----------+------------+
| id | parentId | content |
+----+----------+------------+
| 1 | NULL | comment 1 |
| 2 | NULL | comment 2 |
| 3 | NULL | comment 3 |
| 4 | 2 | comment 4 |
| 5 | 1 | comment 5 |
| 6 | 2 | comment 6 |
| 7 | NULL | comment 7 |
| 8 | 3 | comment 8 |
| 9 | NULL | comment 9 |
| 10 | NULL | comment 10 |
| 11 | NULL | comment 11 |
| 12 | 3 | comment 12 |
| 13 | 2 | comment 13 |
| 14 | 1 | comment 14 |
| 15 | 3 | comment 15 |
+----+----------+------------+
15 rows in set (0.00 sec)
Then we have to use such select statements to order comments (I'm pretty sure this would be the fastest query, correct me someone if I'm wrong):
Code:
mysql> SELECT id, (CASE WHEN parentId IS NULL THEN id ELSE parentId END) AS parent, content FROM comments ORDER BY parent ASC, id ASC;
+----+--------+------------+
| id | parent | content |
+----+--------+------------+
| 1 | 1 | comment 1 |
| 5 | 1 | comment 5 |
| 14 | 1 | comment 14 |
| 2 | 2 | comment 2 |
| 4 | 2 | comment 4 |
| 6 | 2 | comment 6 |
| 13 | 2 | comment 13 |
| 3 | 3 | comment 3 |
| 8 | 3 | comment 8 |
| 12 | 3 | comment 12 |
| 15 | 3 | comment 15 |
| 7 | 7 | comment 7 |
| 9 | 9 | comment 9 |
| 10 | 10 | comment 10 |
| 11 | 11 | comment 11 |
+----+--------+------------+
15 rows in set (0.00 sec)
Then all we have to do is check on the php side:
Code:
foreach ($comments as $comment)
{
if ($comment->id == $comment->parent)
{
// this comment has no parent
// output HTML, e.g. div.parent
}else{
// this comment is a child
// output HTML, e.g. div.child
}
}
assuming that $comments is the object obtained from database using the above query.
And now you may style classes .parent and .child as you wish.
Hope that helps!
EDIT: You may also let SQL do the job by a bit more complex query:
Code:
mysql> select c.id, c.parent, c.content, (CASE WHEN id=parent THEN 1 ELSE 0 END) as isParent FROM ( SELECT id, (CASE WHEN parentId IS NULL THEN id ELSE parentId END) AS parent, content FROM comments ORDER BY parent ASC, id ASC) c;
+----+--------+------------+----------+
| id | parent | content | isParent |
+----+--------+------------+----------+
| 1 | 1 | comment 1 | 1 |
| 5 | 1 | comment 5 | 0 |
| 14 | 1 | comment 14 | 0 |
| 2 | 2 | comment 2 | 1 |
| 4 | 2 | comment 4 | 0 |
| 6 | 2 | comment 6 | 0 |
| 13 | 2 | comment 13 | 0 |
| 3 | 3 | comment 3 | 1 |
| 8 | 3 | comment 8 | 0 |
| 12 | 3 | comment 12 | 0 |
| 15 | 3 | comment 15 | 0 |
| 7 | 7 | comment 7 | 1 |
| 9 | 9 | comment 9 | 1 |
| 10 | 10 | comment 10 | 1 |
| 11 | 11 | comment 11 | 1 |
+----+--------+------------+----------+
15 rows in set (0.00 sec)
then with PHP just check if ($comment->isParent == 1) in the loop.