Can anyone suggest a creative database structure + fetching algorithm for a threaded comments system, that would output x amount of threads per page (with unlimited replies for each)?
I can run a query to get the threads, and in each instance of a loop, run another query to echo out the replies.... but that's a bad idea.
If you need only 2 levels, here's a way with one query:
Your table -
id, parent_id, comment
columnsCode
In
$threads
you will have all your main threads and$threads[$id]['replies']
holds all replies. The threads are sorted - latest = first, add some paging and you're good to go.Add two columns to the comment table: parentCommentId and rootCommentId.
parentCommentId is the id of the parent comment, and rootCommentId is the id of the comment that started this thread.
To display N threads, you'll need two queries:
(You can combine these two into a single GroupBy query.)
This is similar to something I am using now. The only tricky part is calculating the next reply path to insert when somebody replies to a comment.
The Example Data
The Example SQL
The Example PHP
The Example Result
To make a reply to 01_01