Support Forums

Full Version: Creating A Simple PHP/MySQL Forum
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
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.
Very nice
Amazing i 'll save this page
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.
Very nice tutorial, maybe i will try to make some Forum. Thanks
(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.
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.
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.
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
(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.
Makes this into one page, add sanitizing, some pagination, and you're ready for a nice commenting system with threads.
Pages: 1 2 3