Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Basic Custom Forum (PDO)

forum tutorial php pdo script

  • Please log in to reply
1 reply to this topic

#1 gratefulDeadty

gratefulDeadty

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts
  • Programming Language:PHP, Python, Perl
  • Learning:C, Java, Perl

Posted 16 June 2014 - 04:13 PM

I'm developing a website right now, and came to the part where I'll be starting
on the forum. I decided it might be neat to document it as a tutorial, or just
a broad example of what steps you might take in creating the basis for a forum 
board.
 
Breakdown of what we'll be creating, database and script wise.
 
Database:
forum_main
topics
replies
 
Scripts:
forum.php 
topics.php
addtopic.php
forum.class.php
database.php
config.php
 
Script 1: database.php creates a new PDO connection to the mysql database.
<?php
 
/*
* script: database.connection.php
*/
 
$host = 'host';
$dbuser = 'dbuser';
$dbpass = 'dbpass';
$dbname = 'dbname';
 
try
{
$dbh = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
//file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
}
 
?>
 
 
Script 2: config.php This will be our configuration script.
will have our includes (to our database connection, our forum class and our stylesheet.)
It will also call our forum class, and create an error[] array.
<?php 
session_start();
/*
* script: config.php
*
* this is the site configuration file.
* you include it on the top of every page within the forum.
* it handles our forum class, and error[] array.
*/
 
require 'database.php';
require 'forum.class.php';
 
$forums = new Forum($dbh);
$errors = array(); //creates the $errors[] array.
 
ob_start('ob_gzhandler');
 
?>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
 
 
Script 3: forum.class.php This is the forum class, it's our collection of functions.
<?php
/*
* script: forum.class.php
* developed by gratefulDeadty
* 
* this is our forum class, easily custumizable, and easy to add to it.
*/
 
class Forum
{
private $dbh; //dbh = database handler.
public function __construct($database)
{
$this->dbh = $database;
}
 
/* function that gets the main forum board */
public function getForum()
{
$query = $this->dbh->prepare('SELECT * FROM `forum_main` ORDER BY `id` ASC');
try
{
$query->execute();
}
catch(PDOException $e)
{
die($e->getMessage());
}
return $query->fetchAll();
}
 
/* function that gathers the topic list, based off which forum a user is viewing. */
public function getTopics($forumid)
{
$query = $this->dbh->prepare('SELECT * FROM `topics` WHERE `forum`= ?');
$query->bindValue(1, $forumid);
try
{
$query->execute();
return $query->fetchAll();
} 
catch(PDOException $e)
{
die($e->getMessage());
}
}
 
/* function that inserts a new topic */
public function addTopic($username, $title, $message, $whatforum, $created)
{
$query = $this->dbh->prepare('INSERT INTO `topics` (`starter`, `title`, `message`, `forum`, `created`) VALUES (?, ?, ?, ?, ?) ');
$query->bindValue(1, $username);
$query->bindValue(2, $title);
$query->bindValue(3, $message);
$query->bindValue(4, $whatforum);
        $query->bindValue(5, $created);
try
{
$query->execute();
}
catch(PDOException $e)
{
die($e->getMessage());
} 
}
 
/* function that gathers information about the topic */
public function topicData($topicid) 
{
$query = $this->dbh->prepare('SELECT * FROM `topics` WHERE `id`= ?');
$query->bindValue(1, $topicid);
try
{
$query->execute();
return $query->fetch();
} 
catch(PDOException $e)
{
die($e->getMessage());
}
}
 
/* function that gathers information about the replies within the topic. */
public function replyData($topicid) 
{
$query = $this->dbh->prepare('SELECT * FROM `replies` WHERE `topicid`= ?');
$query->bindValue(1, $topicid);
try
{
$query->execute();
}
catch(PDOException $e)
{
die($e->getMessage());
}
return $query->fetchAll();
}
 
 
/* function that inserts a new reply */
public function addReply($message, $username, $topicid, $whatforum, $created)
{
$query = $this->dbh->prepare("INSERT INTO `replies` (`message`, `username`, `topicid`, `forum`, `created`) VALUES (?, ?, ?, ?, ?) ");
$query->bindValue(1, $message);
$query->bindValue(2, $username);
$query->bindValue(3, $topicid);
        $query->bindValue(4, $whatforum);
        $query->bindValue(5, $created);
try
{
$query->execute();
}
catch(PDOException $e)
{
die($e->getMessage());
} 
}
 
 
/* function that adds up the total amount of topics. */
public function totalTopics($forumid)
{
$query = $this->dbh->prepare("SELECT id FROM topics WHERE forum = ?");
        $query->bindValue(1, $forumid);
        try
{
$query->execute();
return $query->rowCount();
} 
catch(PDOException $e)
{
die($e->getMessage());
}
}
 
/* function that adds up the total amount of replies */
public function totalReplies($forumid)
{
$query = $this->dbh->prepare("SELECT id FROM replies WHERE forum = ?");
        $query->bindValue(1, $forumid);
        try
{
$query->execute();
return $query->rowCount();
} 
catch(PDOException $e)
{
die($e->getMessage());
}
}
 
/* function that updates the last post, showing on the main forum board */
public function updatelastPost($whatforum)
{
$query = $this->dbh->prepare('UPDATE `forum_main` SET `lastpost`=? WHERE `id`=? ');
$query->bindValue(1, $username);
$query->bindValue(2, $whatforum);
try
{
$query->execute();
}
catch(PDOException $e)
{
die($e->getMessage());
} 
}
 
/* function that updates the last post, showing on the topics page */
public function updatelastReply($username,$topicid)
{
$query = $this->dbh->prepare('UPDATE `topics` SET `lastpost`=? WHERE `id`=? ');
$query->bindValue(1, $username);
$query->bindValue(2, $topicid);
try
{
$query->execute();
}
catch(PDOException $e)
{
die($e->getMessage());
} 
}
 
 
} //end Forum class.
?> 
 
Script 4: forum.php The forum script. This page will control our actual forum
and the topics.
<?php
 
/*
* script: forum_main.php
* @developed by gratefulDeadty 2014
*/
 
require 'config.php'; //calls to our config file.
 
$forum_main = $forums->getForum();
$topics = $forums->getTopics($_GET['forum']);
 
//check to see if any forum boards exist yet.
if (count($forum_main) == 0)
{
     die('No forums created yet');
}
 
if (empty($_GET['forum']))
{
?>
 
<div align="center">
<table cellspacing="0" cellpadding="0">
<tr>
<td width="100"><strong>Forum</strong></td>
<td width="200"></td>
<td width="50"><strong>Topics</strong></td>
<td width="50"><strong>Posts</strong></td>
<td width="200"><strong>Last Post</strong></td>
</tr>
</div>
 
     <?php
     $color = 1; //start our increment number.
     foreach ($forum_main as $forum) //sets our fetch.
     {
          //alternating colors for table.
          if ($color % 2 != 0)
          $trColor = "#CCCCCC"; 
          else
          $trColor = "#FFFFFF";
          $forum_name = $forum['name'];
          $forum_desc = $forum['description'];
          $forumid = $forum['id'];
          $lastpost = $forum['lastpost'];
          $totaltopics = $forums->totalTopics($forumid);
          $totalreplies = $forums->totalReplies($forumid);

          echo '<tr style="background-color:'.$trColor.';"><td><a href="forum.php?forum='.$forumid.'">' .$forum_name . '</a></td><td>' . $forum_desc . '</td><td>'.$totaltopics.'</td><td>'.$totalreplies.'</div></td><td>last post by ' .$lastpost. '</td>';

          ++$color; //increment.

     } //end foreach()

     echo '</tr></table>';

} //end if()
 
 
if ($_GET['forum'])
{
     if (count($topics) == 0)
     {
          echo '<p>No topics have been found under the '.htmlspecialchars($_GET['forum'],ENT_QUOTES).'</a> forum.</p>';
echo '<br /><br /><a href="addtopic.php?forum='.htmlspecialchars($_GET['forum'],ENT_QUOTES).'">Add Topic</a>';
          die();
     }
     else
     {
     ?>
 
<div align="center">
<table cellspacing="0" cellpadding="0">
<tr>
<td width="100"><strong>Forum</strong></td>
<td width="200"></td>
<td width="50"><strong>Posts</strong></td>
<td width="200"><strong>Last Post</strong></td>
</tr>
</div>
 
     <?php
     $color = 1;
     foreach ($topics as $topic) 
     {
          if ($color % 2 != 0)
          $trColor = "#CCCCCC"; 
          else
          $trColor = "#FFFFFF";
          $topic_id = $topic['id']; //id of topic.
          $topic_title = $topic['title']; //topic title.
          $topic_starter = $topic['starter']; //topic starter.
          $topic_lastpost = $topic['lastpost']; //last replied user
          $totalposts = $forums->totalPosts($topic_id);
          if ($topic['sticky'] == '1')
          {
               $sticky = 'STICKY';
          }
          else
          {
               $sticky = '';
          } 

          echo '<tr style="background-color:'.$trColor.';"><td>'.$sticky.'<a href="topic.php?id='.$topic_id.'">' .$topic_title . '</td><td></td><td>'.$totalposts.'</td><td>Last post by '.$topic_lastpost.'</td>';

         ++$color;

     } //end foreach()
 
     echo '</tr></table>'; 

     echo '<br /><a href="addtopic.php?forum='.htmlspecialchars($_GET['forum'],ENT_QUOTES).'">Post new topic</a> - <a href="forum.php">Forum Main</a>';
 
} //end else()
 
} //end if()
 
?>
 
Script 5: addtopic.php
<?php
 
/*
* script: add_topic.php
* @developed by gratefulDeadty
*/
 
require 'config.php'; 
 
if(empty($_GET['forum']) === true)
{
     $errors[] = 'Error: Forum does not exist.';
}
else
{

     echo '<div><form method="POST">
     Email/Name: <input type="text" name="username"><br />
     Post Title: <input type="text" name="title"><br />
     Post Body: <input type="text" name="message"><br />
     <input type="submit" name="submit" value="Submit"></div>';
}
 
if (isset($_POST['submit']))
{
     if (empty($_POST['username']) || empty($_POST['title']) || empty($_POST['message']))
     {
          $errors[] = 'Error: All fields are required to post.';
     }
     else
     {
          if (empty($errors) === true)
          {
               $username = htmlentities($_POST['username']);
               $title = htmlentities($_POST['title']);
               $message = htmlentities($_POST['message']);
               $whatforum = (int)$_GET['forum'];
               $created = date('Y-m-d H:i:s');
               $forums->addTopic($username,$title,$message,$whatforum,$created);
               $newtopicid = $dbh->lastInsertId();
               
               echo '<p>Thank you, your topic has been added to the '.htmlspecialchars($_GET['forum'],ENT_QUOTES).' forum.</p>';
echo '<br /><a href="forum.php">Back to main board</a> <font color="#898989">or click <a href="topic.php?id='.$newtopicid.'">here</a>';
           }
     }
}
 
//displaying all errors from the $errors[] array.
if (empty($errors) === false)
{ 
     echo ' '.implode($errors).' ';
}
?>
 
Script 6: topic.php
<?php
 
/*
* script: topic.php
* @developed by gratefulDeadty
*/
 
require 'config.php';
 
$topic = $forums->topicData($_GET['id']);
$reply = $forums->replyData($_GET['id']);
 
if(empty($_GET['id']) === true)
{
     $errors[] = 'Error: Forum does not exist. ';
}
else
{
     if (count($topic['id']) == 0)
     {
          $errors[] = 'Error: This topic doesn\'t exist. Click <a href="forum.php">here</a> to go back.';
     }
 
     //success -> now we display the topic, but only if no errors are involved.
     if(empty($errors) === true)
     {
          $starter = $topic['starter'];
          $title = $topic['title'];
          $message = $topic['message'];
          $created = $topic['created'];
          echo '<p><strong>'.$title.'</strong> - <span style="font-size:8pt;"><i>Posted by '.$starter.'</i></span><br />'.$message.'</p>';
 
          $i = 0;
          foreach ($reply as $replies)
          {
               ++$i;
               $reply_username = $replies['username'];
               $reply_message = $replies['message'];
               $created = $replies['created'];
               $whatforum = $replies['forum'];
    
               echo ''.$i.': ' .$reply_username. ' - ' .$reply_message. '<br /><br />';
           }
 
           echo '<br /><div><strong>Reply:</strong><form method="POST">Email/Name: <input type="text" name="username"><br /><br /><textarea name="message" cols="40" rows="4">Body</textarea>
<br /><input type="hidden" name="topicid" value="'.htmlspecialchars($_GET['id'],ENT_QUOTES).'"><input type="submit" name="submit" value="Add Reply"></form></div>';
 
     }
 
}
 
if (isset($_POST['submit']))
{
     //submitting the reply.
     if (empty($_POST['message']) || empty($_POST['username']) === true)
     {
          $errors[] = 'Error: You must enter a reply message and/or an email.';
     }
     else
     {
          //insert the reply into the database.
          $message = htmlentities($_POST['message']);
          $username = htmlentities($_POST['username']);
          $topicid = htmlentities($_POST['topicid']);
          $whatforum = htmlentities($topic['forum']);
          $created = date('Y-m-d H:i:s');
          $insert_reply = $forums->addReply($message,$username,$topicid,$whatforum,$created);
          $forumpost_update = $forums->updatelastPost($username,$whatforum);
          $topicreply_update = $forums->updatelastReply($username,$topicid);
          echo 'You have created a reply!';
     }
 
}
 
//if any errors occured, we'll display them using the $errors[] array.
if (empty($errors) === false)
{
     echo ' '.implode($errors).' ';
}
?>
 
Database:
--
-- Table structure for table `forum_main`
--
 
CREATE TABLE `forum_main` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `description` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `lastpost` varchar(255) COLLATE latin1_general_ci NOT NULL DEFAULT 'n/a',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=3 ;
 
--
-- Dumping data for table `forum_main`
--
 
INSERT INTO `forum_main` VALUES(1, 'Forum 1', 'description for forum 1', '');
INSERT INTO `forum_main` VALUES(2, 'Forum 2', 'description for forum 2', '');
 
-- --------------------------------------------------------
 
--
-- Table structure for table `replies`
--
 
CREATE TABLE `replies` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `topicid` int(11) NOT NULL,
  `username` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `message` text COLLATE latin1_general_ci NOT NULL,
  `forum` int(11) NOT NULL,
  `created` varchar(255) COLLATE latin1_general_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=19 ;
 
 
--
-- Table structure for table `topics`
--
 
CREATE TABLE `topics` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `starter` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `lastpost` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `forum` int(11) NOT NULL,
  `message` text COLLATE latin1_general_ci NOT NULL,
  `created` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `sticky` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=11 ;
 
 
There it is. A very basic forum script. 
 
Sorry that the site mushes everything together, it makes it very unreadable. To view a more neat/readable version I have it posted on my github.
 
 
I also uploaded them.
 
 
 
 

Attached Files


  • 0

#2 Webguy

Webguy

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 23 November 2014 - 11:39 AM

Hello gratefulDeadty

Not bad but needs work.

Has errors some errors.

Notice: Undefined index: forum in /htdocs/forum.php on line 11

Notice: Undefined index: forum in /htdocs/forum.php on line 61

Fatal error: Call to undefined method Forum::totalPosts() in /htdocs/forum.php on line 95


  • 0





Also tagged with one or more of these keywords: forum, tutorial, php, pdo, script