PHP
  Home arrow PHP arrow Page 3 - Developing a Discussion Forum in PHP w...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Moblin 
JMSL Numerical Library 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Developing a Discussion Forum in PHP with Recursion
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 11
    2006-05-15

    Table of Contents:
  • Developing a Discussion Forum in PHP with Recursion
  • Getting started with the forum: defining the structure of the MySQL database table
  • Processing forums threads: defining the "ThreadProcessor" class
  • Displaying the forum: looking at the "fetchTitles()," fetchMessages()" and "createThreadForm()" methods
  • The discussion forum in action: putting the "ThreadProcessor" class to work

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Developing a Discussion Forum in PHP with Recursion - Processing forums threads: defining the "ThreadProcessor" class


    (Page 3 of 5 )

    Basically, I plan to make the forum work by using a single PHP class, called "ThreadProcessor," which is responsible for displaying threads and adding new posts to the pertinent forum. As you'll see shortly, this class will aggregate an additional one, named "MySQL," handy for providing the forum with the capacity to connect to MySQL and run SQL queries.

    Having explained the basic tasks that will be performed by the "ThreadProcessor" class, here is its corresponding definition. Please have a look at it:

    class ThreadProcessor{
        // declare data members
        var $db;
        var $threadCode;
        var $threadSubmitted;
        var $user;
        var $email;
        var $title;
        var $message;
        function ThreadProcessor(&$db){
            $this->db=&$db; // instance of MySQL class
            $this->threadCode=!$_GET['threadcode']?'0':$_GET
    ['threadcode'];
            $this->threadSubmitted=$_POST['send'];
            $this->user=$_POST['user'];
            $this->email=$_POST['email'];
            $this->title=$_POST['title'];
            $this->message=$_POST['message'];
        }
        // display main-child threads & thread form 
        function displayThreads(){
            // add new thread to database
            if($this->threadSubmitted){
                $this->addThread();
            }
            ob_start();
            // display threads
            $this->threadCode=='0'?$this->fetchTitles():$this-
    >fetchMessages();
            // display thread form
            $this->createThreadForm();
            $contents=ob_get_contents();
            ob_end_clean();
            return $contents;
        }
        // display main threads
        function fetchTitles(){
            $result=$this->db->query("SELECT * FROM forum WHERE
    parent_id='$this->threadCode'");
            echo '<ul>';
            // loop over result set
            while($row=$result->fetchRow()){
                echo '<li><a href="'.$_SERVER['PHP_SELF'].'?
    threadcode='.$row['id'].'">'.$row['title'].'</a> Posted by
    ('.$row['name'].') '.$row['email'].'</li>';
                $this->threadCode=$row['id'];
                // call recursively the 'fetchTitles()' method
                $this->fetchTitles();
            }
            echo '</ul>';
        }
        // display child threads
        function fetchMessages(){
            $result=$this->db->query("SELECT name,title,message FROM
    forum WHERE id='$this->threadCode'");
            if($result->countRows()==0){
                echo 'No messages were found!';
                return;              
            }
            $row=$result->fetchRow();
            echo '<h2>'.$row['title'].'</h2><hr /><p>'.$row['name'].'
    wrote: '.$row['message'].'</p><a href="'.$_SERVER['PHP_SELF'].'?
    threadcode=0">Back to main threads</a>';
        }
        // display thread form
        function createThreadForm(){
            $this->threadCode=intval($_GET['threadcode']);
                echo '<form method="post" action="'.$_SERVER
    ['PHP_SELF'].'?threadcode='.$this->threadCode.'"><h2>Post your
    new message</h2>';
                echo 'Name <input type="text" name="user"
    size="30" /><br />Email <input type="text" name="email"
    size="30" /><br />';
                echo 'Title<input type="text" name="title"
    size="30" /><br />Message<br /><textarea  name="message"
    rows="10" cols="30"></textarea><br /><input type="submit"
    name="send" value="Add thread" /></form>';
        }
        // add new thread
        function addThread(){
            $this->db->query("INSERT INTO forum (id,parent_id,name,email,title,message) VALUES (NULL,'$this-
    >threadCode','$this->user','$this->email','$this->title','$this-
    >message')");
            header('location:'.$_SERVER['PHP_SELF']);
        }
    }

    As shown above, the "ThreadProcessor" class exposes a few handy methods for displaying forum threads, as well as for adding new posts to the "forum" database table, something that is achieved by coding a regular online form.

    As I said a few lines above, the class aggregates an instance of a "MySQL" class that comes in quite useful for connecting to MySQL and running queries against the database table. As you can see, this class is aggregated and assigned as a new property inside the respective constructor.

    Now, take a look at the signature of the "displayThreads()" method:

    function displayThreads(){
        // add new thread to database
        if($this->threadSubmitted){
            $this->addThread();
        }
        ob_start();
        // display threads
        $this->threadCode=='0'?$this->fetchTitles():$this-
    >fetchMessages();
        // display thread form
        $this->createThreadForm();
        $contents=ob_get_contents();
        ob_end_clean();
        return $contents;
    }

    In essence, what this method does is determine the course of action to be taken, in accordance with the value of the "threadCode" property. First, it checks whether the form for adding new posts has been submitted, and according to this, calls the "addThread()" method, since a new message has been posted by a user. After checking this condition, the method displays either the corresponding thread titles or the contents of submitted messages. Finally, it shows the form for posting new messages, by calling the "createThreadForm()" method.

    Before proceeding to review other methods of the "ThreadProcessor" class, let me first clarify one point: notice the entire visual output is echoed to an output buffer; the data is not displayed directly on the browser. I have a good reason for doing this: since the "fetchTitles()" method calls itself (yep, here's where recursion comes in), it generates a dynamic output for each method instance, which is easily captured by the output buffer, instead of troubling things with regular variables. Additionally, the remaining methods also use this buffer to output their contents, which are returned to calling code.

    Right, now that you understand the reasons for using an output buffer, the next step consists of looking at the remaining methods of the "ThreadProcessor" class, to give you a clear idea of how they fit together. Therefore, please click on the link below and keep on reading.

    More PHP Articles
    More By Alejandro Gervasio


       · Want to see how recursion can be used in a real-world application? Then this article...
       · It's a great article, I found it really useful. I was trying to write a recursive...
       · Thanks a lot for your positive comments on this PHP article. I must say I feel glad...
     

       

    PHP ARTICLES

    - Validating Web Forms with the Code Igniter P...
    - Output Buffering
    - Paginating Database Records with the Code Ig...
    - HTTP Headers in Web Development
    - Project Management: Administration
    - Building a Database-Driven Application with ...
    - User Authentication for a Project Management...
    - Introduction to the CodeIgniter PHP Framework
    - Adding Users for a Project Management Applic...
    - Migrating Class Code for a MIME Email to PHP...
    - Login and Logout Authentication for a Projec...
    - Composing Messages in HTML for MIME Email wi...
    - Project Management: Authentication
    - A Better Way to Determine MIME Types for MIM...
    - Project Management Overview





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway