Nice, but it runs into a problem - it has to run a query for every post, and if you're dealing with a large thread...
Still, it ran fairly quickly when I tried it on my test forum, which currently has 35 posts. I would probably make a maximum number of replies to show per thread somewhere around 50-100, so the slowdown might not be too bad, but I want to prevent the server from being bogged down.
Here are a few ideas:
At the cost of increasing the amount of space used to store each post, I could include a "replied to" flag with each one. If it's 1, then DisplayThread is called for that post. This would reduce the number of queries by however many "end" posts there are. (Even better, I could make this flag a date - so each post would have a field showing when it was replied to.)
I'm not that familiar with MySQL optimization, so tell me if this wouldn't work well. Use this query:
SELECT DISTINCT t1.* FROM boardposts t1 LEFT JOIN boardposts t2 ON t2.replyTo = 1 WHERE t1.replyTo = t2.id OR t1.replyTo = 1 OR t1.id = 1
To get the post and first 2 levels of replies, then run it again for each reply on the 2nd level. (The PHP involved in organizing the thread would be more complex, but it is possible to do it this way.)
In order for this to be an effective optimization in all situations, this more complex query would have to be no slower than making 3 individual queries, and I'm not sure if that's the case.
- This tutorial - http://reguly.net/alvaro/cic/php/PHP-MySQL-threads.html - uses a recursive method as well, but it suggests opening a permanent connection to the database. I haven't tested yet how much of an impact this might have on speed.