Tree-Style Forum Posts

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
Asylumius
Forum Newbie
Posts: 1
Joined: Sun Jan 01, 2006 2:39 am

Tree-Style Forum Posts

Post by Asylumius »

I'm having an exceptionally hard time designing a db structure and the code to handle the displaying of forum posts based on a expanded tree design. The main problem for me is handling replies to replies to replies, etc.

I'm storing topics as a unique id, and the post id for the first post in that topic. Each post has a reply id which is -1 if its the first post in a topic, otherwise it's the id of the post it is a reply to.

Like I said above, my problem is the logic (and partially syntax) behind displaying everything in a nested fashion. Help appreicated.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

The way you've done it is the way I would handle this on first thoughts too.

I'd use a recursive function to then get all the posts together.....

Untested.

Code: Select all

function getReplies($replyid, $ret=array())
{
    $query = "select id, title from posts where replyid= $replyid"; //Look for reply(s)
    $result = mysql_query($query) or die(mysql_error());
    if (mysql_num_rows($result) > 0) //Check if at least one exists
    {
        while ($row = mysql_fetch_assoc($result)) //Loop over results
        {
            $ret[] = $row['title']; //Store whatever you need
            getReplies($row['id'], $ret); //Recurse
        }
    }
    else return $ret; //Return all results when done
}
Post Reply