Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating A Simple PHP/MySQL Forum
#1
Hey guys;

Today I'll be teaching all you need to know about creating a very simple discussion forum. Unfortunately for some, I did NOT add a login script since it would only make things more complicated.

So, let's get right to the point.

First we need to create the tables:

Code:
CREATE TABLE IF NOT EXISTS `category` (
  `Category` varchar(30) NOT NULL,
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

INSERT INTO `category` (`Category`, `ID`) VALUES
('Test Category #1', 1);

CREATE TABLE IF NOT EXISTS `replies` (
  `User` varchar(50) NOT NULL,
  `TID` varchar(11) NOT NULL,
  `Date` date NOT NULL,
  `Reply` varchar(500) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `threads` (
  `User` varchar(60) NOT NULL,
  `Date` date NOT NULL,
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Title` varchar(50) NOT NULL,
  `Content` varchar(5000) NOT NULL,
  `CID` varchar(11) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

And there you go. That's all you'll need in MySQL.

Now, time to work with PHP.

First, let's make header.php and footer.php which we'll include in all our files.

Header.php:
Code:
<html>
<head>
<title>My First Forum</title>
</head>
<body>

Footer.php:
Code:
</body>
</html>

This will make your job faster. So like, if you want to change the title, instead of going through each file and changing the title, you can just do it on header.php.

Your forum's got to have an index.php right?

Index.php:
Code:
<?php include('header.php');
$con = mysql_connect("localhost","dbusername","dbpassword");

mysql_select_db("db", $con);
?>
<table cellspacing="6" cellpadding="5">
<th>Categories</th>
<?php
$showcats = mysql_query("SELECT * FROM category ORDER BY ID ASC");
while($row = mysql_fetch_array($showcats))
  { ?>
    <tr>
        <td width="500px"><?php echo "<a href=\"category.php?id=" . $row['ID'] . "\">" . $row['Category'] . "</a>" ?></td>
    </tr>
<?php
}
?>
  </table>
<br />
<A href="logout.php" />Logout</a>
<?php
include('footer.php'); ?>

It should open fine and you should be able to see Test Category #1.

Now if you click on Test Category #1, you WILL get an error stating that there is no such file. Maybe we should make one?

Category.php:
Code:
<?php include('header.php');

    $con = mysql_connect("localhost","dbusername","dbpassword");
$id = (isset($_GET['id']) && is_numeric($_GET['id']) ? $_GET['id'] : 0);
$id = mysql_real_escape_string($id);
mysql_select_db("db", $con);
$showthread = mysql_query("SELECT * FROM threads WHERE CId=$id ORDER BY Date DESC");
if (mysql_num_rows($showthread) < 1)
{
    echo "<i><h2>There are no threads in this category.</h2></i>";
    echo "<br />
<a href='createtopic.php?id=$id'>Would you like to create a thread?</a>";
    }
else {
?>
<table cellspacing="6" cellpadding="5">
    <tr>
        <th>Thread</th>
        <th>Created By</th>
    </tr>
<?php

while($row = mysql_fetch_array($showthread))

  { ?>

    
    <tr>
        <td width="500px"><?php echo "<a href=\"thread.php?id=" . $row['ID'] . "\">" . $row['Title'] . "</a>" ?></td>
        <td width="300px"><?php echo "<center>" . $row['User'] . "<br /> on " . $row['Date'] . "</center>" ?></td>
    </tr>

    <?php
}
?>
</table>
<br />
<a href="createthread.php?id=<?php echo "$id" ?>">Would you like to create a thread?</a>
<?php
}
?>
<?php include('footer.php');   ?>

You should be able to see an error stating that there are no threads in this category. It's a little soon to be making the threads script, so let's just go into phpMyAdmin and:

Code:
INSERT INTO `threads` (`User`, `Date`, `ID`, `Title`, `Content`, `CID`) VALUES
('Andy', '2010-05-15', 1, 'Test Thread #1', 'Works.', '1')

Refresh the page and you should see the thread. Let's make thread.php so you can see the thread's content:

Thread.php:
Code:
<?php include('header.php');
    $con = mysql_connect("localhost","dbusername","dbpassword");

mysql_select_db("db", $con);
?>
<table cellpadding="5" cellspacing="6">
<?php
$id = (isset($_GET['id']) && is_numeric($_GET['id']) ? $_GET['id'] : 0);
$id = mysql_real_escape_string($id);
$showthread = mysql_query("SELECT * FROM threads WHERE ID=$id");
while($row = mysql_fetch_array($showthread))

  {
?>
<tr>    <th> Posted By </th>
        <th> Content </th>
<tr>    <td width="300px"> <?php echo "<center>" . $row['User'] . "<br /> on " . $row['Date'] . "</center>" ?> </td>
        <td width="500px"> <?php echo $row['Content'] ?> </td>
        <?php
    };
$showreplies = mysql_query("SELECT * FROM replies WHERE TID=$id");
while($row = mysql_fetch_array($showreplies))
{
?>
<tr>
        <td width="300px"> <?php echo "<center>" . $row['User'] . "<br /> on " . $row['Date'] . "</center>" ?> </td>
        <td width="500px"> <?php echo $row['Reply'] ?> </td>
</tr>


<?php };  ?>
</table>
<br />
<form action="addreply.php" method="post">
<label for="user">Username:</label><br />
<input type="text" name="username" /><br />
<label for="reply">Reply:</label><br />
<textarea id="reply" cols="30" rows="10" name="reply"></textarea>
<input type="hidden" value="<?php echo "$id" ?>" name="id" />
<input type="submit" value="Reply" />
</form>  
<?php include('footer.php'); ?>

There you go.

Couple of steps to go, the add reply and the create topic scripts.

Addreply.php:
Code:
<?php
include('header.php');
$con = mysql_connect("localhost","dbusername","dbpassword");
$name = $_POST['username'];
$name = mysql_real_escape_string($name);    
$id = $_POST['id'];
$id = mysql_real_escape_string($id);
$reply = $_POST['reply'];
$reply = mysql_real_escape_string($reply);
$date = date("Y/m/d H:i:s");
mysql_select_db("db", $con);

mysql_query("INSERT INTO replies (User, Date, Reply, TID)
VALUES ('$name', '$date', '$reply', '$id')");

mysql_close($con);
echo "Reply added.";
echo "<br /><a href='thread.php?id=$id'>View Reply</a>";
include('footer.php');
?>

You SHOULD be able to add replies easily now.

Createthread.php:
Code:
<?php include('header.php');

    $con = mysql_connect("localhost","dbusername","dbpassword");
mysql_select_db("db", $con);
$id = (isset($_GET['id']) && is_numeric($_GET['id']) ? $_GET['id'] : 0);
$id = mysql_real_escape_string($id);
?>
<form action="createproc.php" method="post">
    <label for="title">Title:</label> <input id="title" type="text" name="title" /><br /><br />
    <label for="username">Username:</label> <input id="username" type="text" name="username" /><br /><br />
    <label for="contentt">Content:</label><br /> <textarea id="contentt" name="content" cols="30" rows="10"></textarea><br /><br />
    <input type="hidden" name="id" value="<?php echo "$id" ?>" />
    <input type="submit" value="Create!" />
</form>
<?php include('footer.php'); ?>

Createproc.php:
Code:
<?php
    $con = mysql_connect("localhost","dbusername","dbpassword");

mysql_select_db("db", $con);
$postedby = $_POST['username'];
$postedby = mysql_real_escape_string($postedby);
$title = $_POST['title'];
$title = mysql_real_escape_string($title);
$date = date("Y/m/d H:i:s");
$content = $_POST['content'];
$content = mysql_real_escape_string($content);
$content = nl2br($content);
$id = $_POST['id'];
$id = mysql_real_escape_string($id);
mysql_select_db("k", $con);

mysql_query("INSERT INTO threads (Title, User, Date, Content, CID)
VALUES ('$title', '$postedby', '$date', '$content', '$id')");

$result = mysql_query("SELECT * FROM threads WHERE Title='$title' and User='$postedby' and Content='$content'");
while($row = mysql_fetch_array($result))
  {
  $tid = $row['ID'];
  header("Location: thread.php?id=$tid");
  }
include('footer.php'); ?>

And there you have it. You should now have an up-and-running simple forum.

Note: This is not really a tutorial as it is a script, + I did not add any CSS, so it should look plain and white.
Reply
#2
Very nice
Amazing i 'll save this page
Reply
#3
I can respect your decision to keep this tutorial short but ignoring basic security protocols is not the way to teach people. You never, under any circumstances, insert raw form-fed data into a database. Instead you should be sanitizing all form data before it makes it to the database.

There are a wide variety of options when it comes to sanitizing data. And it'll often times depend on the application at hand; that is, whether you just settle for escaping quotes or go with a more sturdy character white list.

For the sake of simplicity look into the mysql_real_escape_string function. It's the most basic way to prevent SQL injections and limit XSS vulnerability. And like I said: it's simple. Simple enough to be used in this tutorial.
Reply
#4
Very nice tutorial, maybe i will try to make some Forum. Thanks
Reply
#5
(05-16-2010, 02:33 AM)BHensley Wrote: I can respect your decision to keep this tutorial short but ignoring basic security protocols is not the way to teach people. You never, under any circumstances, insert raw form-fed data into a database. Instead you should be sanitizing all form data before it makes it to the database.

There are a wide variety of options when it comes to sanitizing data. And it'll often times depend on the application at hand; that is, whether you just settle for escaping quotes or go with a more sturdy character white list.

For the sake of simplicity look into the mysql_real_escape_string function. It's the most basic way to prevent SQL injections and limit XSS vulnerability. And like I said: it's simple. Simple enough to be used in this tutorial.

The tutorial was kind of a quickie. Anyway, I read the codes again and I'm pretty sure I added mysql_real_escape_string where it should be.

Thanks for the advice.
Reply
#6
Really detailed tutorial. I would like to add that you can always use phpbb and edit footer to get rid of "Powered by Phpbb", but it's good to know these things, thanks.
Reply
#7
Nice tutorial. I have seen a few of these online.

However, you mustn't ignore security principals (as said earlier). I personally would use prepared statements to prevent SQL attacks.

(05-17-2010, 02:30 AM)notLuke Wrote: Really detailed tutorial. I would like to add that you can always use phpbb and edit footer to get rid of "Powered by Phpbb", but it's good to know these things, thanks.

I'm pretty sure this violates the terms of the phpBB licence.
Reply
#8
Very nice, I might use this as a base then build onto it, I tried writing my own base once, but it was kinda rubbish, since im new to learning PHP.

Thanks Smile
Reply
#9
(05-16-2010, 02:33 AM)BHensley Wrote: I can respect your decision to keep this tutorial short but ignoring basic security protocols is not the way to teach people. You never, under any circumstances, insert raw form-fed data into a database. Instead you should be sanitizing all form data before it makes it to the database.

There are a wide variety of options when it comes to sanitizing data. And it'll often times depend on the application at hand; that is, whether you just settle for escaping quotes or go with a more sturdy character white list.

For the sake of simplicity look into the mysql_real_escape_string function. It's the most basic way to prevent SQL injections and limit XSS vulnerability. And like I said: it's simple. Simple enough to be used in this tutorial.

Another amazing answer to another pointless tutorial.
Reply
#10
Makes this into one page, add sanitizing, some pagination, and you're ready for a nice commenting system with threads.
Superman I am here to rescue you.
This is Support Forums not Support PMs.  Do not PM me for support unless it's private and site related.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PHP Framework List: An Ultimate Guide to 102 PHP Frameworks for Web Developers tk-hassan 0 936 07-27-2020, 11:26 PM
Last Post: tk-hassan
  Creating Dynamic images with PHP Gaijin 15 8,188 01-21-2012, 06:17 PM
Last Post: Dube
  PHP Video Tutorials (PHP For Beginners) Eleqtriq 4 3,659 10-10-2011, 01:00 PM
Last Post: Greyersting
  optimize mysql through a php script andrewjs18 7 3,331 10-05-2011, 06:31 PM
Last Post: John.
  [PHP] SIMPLE NEWS SYSTEM Leprechaun Coder 4 2,755 05-15-2011, 04:46 PM
Last Post: Tunasty™

Forum Jump:


Users browsing this thread: 1 Guest(s)