Creating a Simple Threaded Discussion Forum

Most websites have some method of interacting with a visitor. Some have a chat system and others have shoutboxes or other ways to attract the visitor to return. One of the most used methods is a discussion forum. And this is what we are going to create and discuss in this article (the first of two parts).

Specifically, we’re going to create a threaded discussion forum. Why do we want a THREADED discussion forum? Well, it’s simple: a threaded discussion forum allows a visitor to make multiple replies to the same topic in an ordered fashion. This gives us a discussion tree, with the topic being at the heart of it.

The Code

Our Forum is going to have four main pages:

  • Index.php – To let users view a list of all the parent thread (topic) titles.
  • Viewarticle.php – To let users view a full parent message and replies.
  • Postre.php – To let users reply to a parent thread.
  • Post.php – To let users create a new thread (or topic).

We will need some additional files:

  • Tutstyle.css – CSS style definitions.
  • fns_all.php – Contains all the functions used in the forum.
  • config.php – Contains the database connection settings.

We will also create an “images” folder in the same directory.

Here’s the table for our forum:

CREATE TABLE `test` (
  `uid` int(5) unsigned NOT NULL auto_increment,
  `parent` int(5) NOT NULL default ‘0’,
   `name` varchar(90) NOT NULL default ”,
  `title` varchar(100) NOT NULL default ”,
  `message` text NOT NULL,
  `date` datetime NOT NULL default ‘0000-00-00 00:00:00′,
  PRIMARY KEY  (`uid`)

The field called “uid” is a unique, autonumber field, which will identify each thread in the discussion forum. The field “parent” represents the ID of the parent thread for the current thread (if any), and will be 0 for all new threads. This structure gives us the ability to add as many replies to a thread as we like.

Copy and paste the table structure in your phpAdmin client:

{mospagebreak title=Index.php}

The first page in this application will display all the main threads. See image below:

To display the new threads, we run a database query that retrieves all topics with a parent ID equal to 0 (remember we said that all new threads will be equal to 0?). In addition, we will also create a pagination system that will allow us to view only a set number of threads per page. So the gettopics function below does two things: it shows us the main threads, and it sets the page number. Have a look at the function code below:

function gettopics($topicid){
include(“config.php”);
$Per_Page=5; //number of topics to show on a page
 // Run The Query Without a  Limit to get Total result
 $SQL=”SELECT COUNT(*) AS Total FROM test where parent=0 “;
$SQL_Result=mysql_db_query($dbname, $SQL);
$SQL_Result_Array=mysql_fetch_array($SQL_Result);
$Total=$SQL_Result_Array['Total'];
  // Create a new SELECT Query with the
   // ORDER BY clause and without the COUNT(*)
$SQL=”SELECT * FROM test where parent=$topicid ORDER BY date
desc”;
//Append a LIMIT clause to the sql statement
 if (empty($_GET['Result_Set'])) {
 $Result_Set=0;
 $SQL.=” LIMIT $Result_Set, $Per_Page”;
  }
  else
 {
 $Result_Set=$_GET['Result_Set'];
 $SQL.=” LIMIT $Result_Set, $Per_Page”;
 }
 // Run The Query With a Limit to get result
 $SQL_Result=mysql_db_query($dbname,$SQL);
 $SQL_Rows=mysql_num_rows($SQL_Result);
echo “<table width=”760″ >”;
echo “<tr bgcolor=”#3399CC”>
<td width=”190″><center><b>Subject</b></center></td>
<td width=”190″><center><b>Name</b></center></td>
<td width=”190″><center><b>Date</b></center></td>
<td width=”190″><center><b>Replies</b></center></td>”;
echo ‘</tr>';
echo “</table>”;
 // Display Results using a for loop
 for ($a=0; $a < $SQL_Rows; $a++) {
$SQL_Array=mysql_fetch_array($SQL_Result);
$title=$SQL_Array['title'];
$name=$SQL_Array['name'];
$uid=$SQL_Array['uid'];
$message=$SQL_Array['message'];
$date=$SQL_Array['date'];
//query to get all replies
$query2=”select * from test where parent=$uid order by
date,parent desc “;
$result=mysql_query($query2);
 $num = mysql_num_rows($result);
$num = mysql_num_rows($result);
 if($num >0){
 $replies= “$num”;
 $image=”<img src=”fb.gif”>”;
 }else{
 $replies= “0”;
 $image=”<img src=”http://www.devshed.com/wp-content/themes/twentyten/images/doc.gif”>”;
 }
 echo “<table width=”760″ >”;
echo “<tr>
      <td width=”190″>$image<a href=”viewarticle.php?
parent=$uid”> $title </a> </td>
    <td width=”190″><b>$name</b></td>
    <td width=”190″>$date</td>
    <td width=”190″><b>$replies</b> replies <br/></td>”;
 echo ‘</tr>';
echo “</table>”;
 }
echo ‘<br>';
echo ‘<div id=”Pageno”>';
 // Create Next / Prev Links and $Result_Set Value
 if ($Total>0)
 {
 if ($Result_Set<$Total&& $Result_Set>0) {
$Res1=$Result_Set-$Per_Page;
echo ‘<A HREF=”index.php?Result_Set=’.$Res1.'”> << Previous
Page</A> ‘;
}
 // Calculate and Display Page # Links
 $Pages=$Total / $Per_Page;
 if ($Pages>1) {
  for ($b=0,$c=1; $b < $Pages; $b++,$c++) {
   $Res1=$Per_Page * $b;
 echo ‘<A HREF=”index.php?Result_Set=’.$Res1.'”> ‘.$c.'</A> ‘;
}
 }
 if ($Result_Set>=0 && $Result_Set<$Total) {
 $Res1=$Result_Set+$Per_Page;
if ($Res1<$Total) {
echo ‘<A HREF=”index.php?Result_Set=’.$Res1.'”> Next Page >></A>';
echo ‘</div>';
 }
  }
   }
   }

Let me explain how this function works. First the function deals with the pagination issue. The $Per_Page variable sets the number of records you want to display on a page. The function also builds the table that will host all of the records and data. In addition, it also retrieves the replies made to all the individual threads. The function looks difficult but is really very simple; there are comments on the code to make it easy for you to understand what is going on.

{mospagebreak title=viewarticle.php}

The screen shot above shows the viewarticles page listing the replies to a thread.  The function below is responsible for doing exactly that:

//view replies to selected threads -viewarticles.php
function
viewthread(){
      include(“config.php”);
        $query=”select * from test where uid =$parent”;
      if ($r =mysql_query($query)) {
 //Retrieve records
 while ($row =mysql_fetch_array($r)) {
//transfer values
 $child=$row['child'];
//$parent=$row['parent'];
$uid=$row['uid'];
$name=$row['name'];
$title=$row['title'];
$message=$row['message'];
$date=$row['date'];
//put values in session vars
$_SESSION['title']=$title;
$_SESSION['message']=$message;
$_SESSION['parent']=$parent;
$child=$_SESSION['parent'];
$child=$child + 1;
$_SESSION['child']=$child;
//display values
     echo “<b>Title:</b> $title<br> <b>By:</b> $name <br> <b>Date
Posted:</b> $date<br />”;
         echo “<b>Message:</b> $message <br />”;
         }
         }
         }

It’s relatively straightforward. This function receives a $parent number from the index.php page and uses that number to retrieve all records with a uid equal to the  $parent value, as in:  $query=”select * from test where uid =$parent”;

Also, on the same page the code below is used to get all the replies related to the current thread:

$parent =$_GET['parent'];
include(“config.php”);
 $query=”select uid,name,title,message,parent,date from test
where parent=$parent order by date,parent desc “;
 if ($r =mysql_query($query)) {
 //$num = mysql_num_rows($r);
 //Retrieve records
 while ($row =mysql_fetch_array($r)) {
$name=$row['name'];
$uid=$row['uid'];
$title=$row['title'];
$message=$row['message'];
$date=$row['date'];
//add bullet points
echo  ‘<ul type=”disc”>';
echo “<li>”;
//echo “<a href=”index.php?parent=$uid”> $title </a>”;
echo “<a href=”viewarticle.php?parent=$uid”> $title </a> “;
echo “– by <b>$name</b> $date<br/>”;
echo “</li></ul>”;
}
}

This code receives the $parent value from the index page and uses that value to retrieve all records whose parent value matches the value in the $parent variable. I hope this is not too confusing. Say a new thread is created, and given a uid of 7. All the replies to this thread will have 7 in the parent column of the database. Therefore, if you want to find all the replies to this thread, all you have to do is to retrieve all the records that have seven in their parent column. And this is what happens here.

{mospagebreak title=Postre.php}

This page enables you to reply to a specific thread. The thread number is passed on from the viewarticle page. Here we create a form and populate its title field with the  $_SESSION['title'] variable.

<form name=”form1″ method=”post” action=”ins.php”>
     <input type=”text” name=”name”>
    <input type=”text” name=”title” value=”<? echo “RE: ” .
$_SESSION['title'] .”” ;?>”>
 <input name=”parent” type=”hidden” value='<? echo $parent//””.
$_GET['parent']. “”;?>’>
  </div>
<div align=”center”><a href=”index.php”>Topic Listings</a>|<a
href=”post.php?parent=0″>Post New Topic</a> </div>
</div>
<div id=”content2″>
  <p>
 <center><textarea name=”message” cols=”75″ rows=”9″></textarea></center>
</p>
</div>
<div id=”footer”>
 <center> <input type=”submit” name=”submit” value=”submit”></form></center>

Once submitted, the form values are processed in the ins.php page and then inserted in the database.

post.php

This page is for new posts; it will send the form data off to the insert.php page, which will process and enter the details into the database.

And by the way…I’ve just created this function as something additional. The function will enable you to add… wait for it… smilies! All that the function does is to search for the “:D” or the “:A” delimiters and then replace that text with the images that has been assigned.  You can extend this function by adding your own images and delimiters later on, to give your users a wider choice of smilies. Here’s the function:

function insertsmilie($smilie) {
$smilie = str_replace(“:D”, “<img src=”imagessmile.gif”>”,
$smilie);
$smilie  = str_replace(“:A”,”<img src=”imagesangry.gif” >”,
$smilie);
return $smilie;
}

fns_all.php

The script contains all the functions used throughout the application. I’ve already explained the main function called gettopics() and what it does. There is another function that I think needs a bit of explaining, the “badwords_filter($msg)” function. This function does exactly what its name implies, it replaces offensive words in a message that is posted. It is used in the ins.php script. It retrieves a list of bad words stored in a text file and then checks to see if any of them are included in the newly posted message. If it finds one, it replaces that word with XXX. Here’s the code that does the job:

function badwords_filter($msg)
{
    $obscenities = file(“test.txt”);
    $newmsg = $msg;
    foreach ($obscenities as $key=>$val)
    {
        $newmsg = str_replace(trim($val), “XXX”, $newmsg);
    }
    return $newmsg;
}

Conclusion

Finally, I would suggest that you create a login script to go with this forum for the admin area.

Below is an example of an administrators area:

And this is what we will create next for our forum, in the next article. Till then have fun!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye