We've created some categories, so now we're able to display them on the front page. Let's add the following query to the content area of index.php.
- SELECT
- categories.cat_id,
- categories.cat_name,
- categories.cat_description,
- FROM
- categories
This query selects all categories and their names and descriptions from the categories table. We only need a bit of PHP to display the results. If we add that part just like we did in the previous steps, the code will look like this.
- <?php
- //create_cat.php
- include 'connect.php';
- include 'header.php';
- $sql = "SELECT
- cat_id,
- cat_name,
- cat_description,
- FROM
- categories";
- $result = mysql_query($sql);
- if(!$result)
- {
- echo 'The categories could not be displayed, please try again later.';
- }
- else
- {
- if(mysql_num_rows($result) == 0)
- {
- echo 'No categories defined yet.';
- }
- else
- {
- //prepare the table
- echo '<table border="1">
- <tr>
- <th>Category</th>
- <th>Last topic</th>
- </tr>';
- while($row = mysql_fetch_assoc($result))
- {
- echo '<tr>';
- echo '<td class="leftpart">';
- echo '<h3><a href="category.php?id">' . $row['cat_name'] . '</a></h3>' . $row['cat_description'];
- echo '</td>';
- echo '<td class="rightpart">';
- echo '<a href="topic.php?id=">Topic subject</a> at 10-10';
- echo '</td>';
- echo '</tr>';
- }
- }
- }
- include 'footer.php';
- ?>
Notice how we're using the cat_id to create links to category.php. All the links to this page will look like this: category.php?cat_id=x, where x can be any numeric value. This may be new to you. We can check the url with PHP for $_GET values. For example, we have this link:
- category.php?cat_id=23
The statement echo $_GET[ëcat_id'];' will display '23'. In the next few steps we'll use this value to retrieve the topics when viewing a single category, but topics can't be viewed if we haven't created them yet. So let's create some topics!
Step 9: Creating a Topic
In this step, we're combining the techniques we learned in the previous steps. We're checking if a user is signed in, we'll use an input query to create the topic and create some basic HTML forms.
The structure of create_topic.php can hardly be explained in a list or something, so I rewrote it in pseudo-code.
- <?php
- if(user is signed in)
- {
- //the user is not signed in
- }
- else
- {
- //the user is signed in
- if(form has not been posted)
- {
- //show form
- }
- else
- {
- //process form
- }
- }
- ?>
Here's the real code of this part of our forum, check the explanations below the code to see what it's doing.
- <?php
- //create_cat.php
- include 'connect.php';
- include 'header.php';
- echo '<h2>Create a topic</h2>';
- if($_SESSION['signed_in'] == false)
- {
- //the user is not signed in
- echo 'Sorry, you have to be <a href="/forum/signin.php">signed in</a> to create a topic.';
- }
- else
- {
- //the user is signed in
- if($_SERVER['REQUEST_METHOD'] != 'POST')
- {
- //the form hasn't been posted yet, display it
- //retrieve the categories from the database for use in the dropdown
- $sql = "SELECT
- cat_id,
- cat_name,
- cat_description
- FROM
- categories";
- $result = mysql_query($sql);
- if(!$result)
- {
- //the query failed, uh-oh :-(
- echo 'Error while selecting from database. Please try again later.';
- }
- else
- {
- if(mysql_num_rows($result) == 0)
- {
- //there are no categories, so a topic can't be posted
- if($_SESSION['user_level'] == 1)
- {
- echo 'You have not created categories yet.';
- }
- else
- {
- echo 'Before you can post a topic, you must wait for an admin to create some categories.';
- }
- }
- else
- {
- echo '<form method="post" action="">
- Subject: <input type="text" name="topic_subject" />
- Category:';
- echo '<select name="topic_cat">';
- while($row = mysql_fetch_assoc($result))
- {
- echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
- }
- echo '</select>';
- echo 'Message: <textarea name="post_content" /></textarea>
- <input type="submit" value="Create topic" />
- </form>';
- }
- }
- }
- else
- {
- //start the transaction
- $query = "BEGIN WORK;";
- $result = mysql_query($query);
- if(!$result)
- {
- //Damn! the query failed, quit
- echo 'An error occured while creating your topic. Please try again later.';
- }
- else
- {
- //the form has been posted, so save it
- //insert the topic into the topics table first, then we'll save the post into the posts table
- $sql = "INSERT INTO
- topics(topic_subject,
- topic_date,
- topic_cat,
- topic_by)
- VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
- NOW(),
- " . mysql_real_escape_string($_POST['topic_cat']) . ",
- " . $_SESSION['user_id'] . "
- )";
- $result = mysql_query($sql);
- if(!$result)
- {
- //something went wrong, display the error
- echo 'An error occured while inserting your data. Please try again later.' . mysql_error();
- $sql = "ROLLBACK;";
- $result = mysql_query($sql);
- }
- else
- {
- //the first query worked, now start the second, posts query
- //retrieve the id of the freshly created topic for usage in the posts query
- $topicid = mysql_insert_id();
- $sql = "INSERT INTO
- posts(post_content,
- post_date,
- post_topic,
- post_by)
- VALUES
- ('" . mysql_real_escape_string($_POST['post_content']) . "',
- NOW(),
- " . $topicid . ",
- " . $_SESSION['user_id'] . "
- )";
- $result = mysql_query($sql);
- if(!$result)
- {
- //something went wrong, display the error
- echo 'An error occured while inserting your post. Please try again later.' . mysql_error();
- $sql = "ROLLBACK;";
- $result = mysql_query($sql);
- }
- else
- {
- $sql = "COMMIT;";
- $result = mysql_query($sql);
- //after a lot of work, the query succeeded!
- echo 'You have successfully created <a href="topic.php?id='. $topicid . '">your new topic</a>.';
- }
- }
- }
- }
- }
- include 'footer.php';
- ?>
I'll discuss this page in two parts, showing the form and processing the form.
Showing the form
We're starting with a simple HTML form. There is actually something special here, because we use a dropdown. This dropdown is filled with data from the database, using this query:
- SELECT
- cat_id,
- cat_name,
- cat_description
- FROM
- categories
That's the only potentially confusing part here; it's quite a piece of code, as you can see when looking at the create_topic.php file at the bottom of this step.
Processing the form
The process of saving the topic consists of two parts: saving the topic in the topics table and saving the first post in the posts table. This requires something quite advanced that goes a bit beyond the scope of this tutorial. It's called a transaction, which basically means that we start by executing the start command and then rollback when there are database errors and commit when everything went well. More about transactions.
- <?php
- //start the transaction
- $query = "BEGIN WORK;";
- $result = mysql_query($query);
- //stop the transaction
- $sql = "ROLLBACK;";
- $result = mysql_query($sql);
- //commit the transaction
- $sql = "COMMIT;";
- $result = mysql_query($sql);
- ?>
The first query being used to save the data is the topic creation query, which looks like this:
- INSERT INTO
- topics(topic_subject,
- topic_date,
- topic_cat,
- topic_by)
- VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
- NOW(),
- " . mysql_real_escape_string($_POST['topic_cat']) . ",
- " . $_SESSION['user_id'] . ")
At first the fields are defined, then the values to be inserted. We've seen the first one before, it's just a string which is made safe by using mysql_real_escape_string(). The second value, NOW(), is a SQL function for the current time. The third value, however, is a value we haven't seen before. It refers to a (valid) id of a category. The last value refers to an (existing) user_id which is, in this case, the value of $_SESSION[ëuser_id']. This variable was declared during the sign in process.
If the query executed without errors we proceed to the second query. Remember we are still doing a transaction here. If we would've got errors we would have used the ROLLBACK command.
- INSERT INTO
- posts(post_content,
- post_date,
- post_topic,
- post_by)
- VALUES
- ('" . mysql_real_escape_string($_POST['post_content']) . "',
- NOW(),
- " . $topicid . ",
- " . $_SESSION['user_id'] . ")
The first thing we do in this code is use mysql_insert_id() to retrieve the latest generated id from the topic_id field in the topics table. As you may remember from the first steps of this tutorial, the id is generated in the database using auto_increment.
Then the post is inserted into the posts table. This query looks a lot like the topics query. The only difference is that this post refers to the topic and the topic referred to a category. From the start, we decided to create a good data model and here is the result: a nice hierarchical structure.
![]() |
We're going to make an overview page for a single category. We've just created a category, it would be handy to be able to view all the topics in it. First, create a page called category.php.
A short list of the things we need:
Needed for displaying the category
- cat_name
- cat_description
Needed for displaying all the topics
- topic_id
- topic_subject
- topic_date
- topic_cat
Let's create the two SQL queries that retrieve exactly this data from the database.
- SELECT
- cat_id,
- cat_name,
- cat_description
- FROM
- categories
- WHERE
- cat_id = " . mysql_real_escape_string($_GET['id'])
The query above selects all the categories from the database.
- SELECT
- topic_id,
- topic_subject,
- topic_date,
- topic_cat
- FROM
- topics
- WHERE
- topic_cat = " . mysql_real_escape_string($_GET['id'])
The query above is executed in the while loop in which we echo the categories. By doing it this way, we'll see all the categories and the latest topic for each of them.
The complete code of category.php will be the following:
- <?php
- //create_cat.php
- include 'connect.php';
- include 'header.php';
- //first select the category based on $_GET['cat_id']
- $sql = "SELECT
- cat_id,
- cat_name,
- cat_description
- FROM
- categories
- WHERE
- cat_id = " . mysql_real_escape_string($_GET['id']);
- $result = mysql_query($sql);
- if(!$result)
- {
- echo 'The category could not be displayed, please try again later.' . mysql_error();
- }
- else
- {
- if(mysql_num_rows($result) == 0)
- {
- echo 'This category does not exist.';
- }
- else
- {
- //display category data
- while($row = mysql_fetch_assoc($result))
- {
- echo '<h2>Topics in ′' . $row['cat_name'] . '′ category</h2>';
- }
- //do a query for the topics
- $sql = "SELECT
- topic_id,
- topic_subject,
- topic_date,
- topic_cat
- FROM
- topics
- WHERE
- topic_cat = " . mysql_real_escape_string($_GET['id']);
- $result = mysql_query($sql);
- if(!$result)
- {
- echo 'The topics could not be displayed, please try again later.';
- }
- else
- {
- if(mysql_num_rows($result) == 0)
- {
- echo 'There are no topics in this category yet.';
- }
- else
- {
- //prepare the table
- echo '<table border="1">
- <tr>
- <th>Topic</th>
- <th>Created at</th>
- </tr>';
- while($row = mysql_fetch_assoc($result))
- {
- echo '<tr>';
- echo '<td class="leftpart">';
- echo '<h3><a href="topic.php?id=' . $row['topic_id'] . '">' . $row['topic_subject'] . '</a><h3>';
- echo '</td>';
- echo '<td class="rightpart">';
- echo date('d-m-Y', strtotime($row['topic_date']));
- echo '</td>';
- echo '</tr>';
- }
- }
- }
- }
- }
- include 'footer.php';
- ?>
And here is the final result of our categories page:
![]() |
The SQL queries in this step are complicated ones. The PHP-part is all stuff that you've seen before. Let's take a look at the queries. The first one retrieves basic information about the topic:
- SELECT
- topic_id,
- topic_subject
- FROM
- topics
- WHERE
- topics.topic_id = " . mysql_real_escape_string($_GET['id'])
This information is displayed in the head of the table we will use to display all the data. Next, we retrieve all the posts in this topic from the database. The following query gives us exactly what we need:
This time, we want information from the users and the posts table - so we use the LEFT JOIN again. The condition is: the user id should be the same as the post_by field. This way we can show the username of the user who replied at each post.
- SELECT
- posts.post_topic,
- posts.post_content,
- posts.post_date,
- posts.post_by,
- users.user_id,
- users.user_name
- FROM
- posts
- LEFT JOIN
- users
- ON
- posts.post_by = users.user_id
- WHERE
- posts.post_topic = " . mysql_real_escape_string($_GET['id'])
The final topic view looks like this:
![]() |
Let's create the last missing part of this forum, the possibility to add a reply. We'll start by creating a form:
- <form method="post" action="reply.php?id=5">
- <textarea name="reply-content"></textarea>
- <input type="submit" value="Submit reply" />
- </form>
![]() |
- <?php
- //create_cat.php
- include 'connect.php';
- include 'header.php';
- if($_SERVER['REQUEST_METHOD'] != 'POST')
- {
- //someone is calling the file directly, which we don't want
- echo 'This file cannot be called directly.';
- }
- else
- {
- //check for sign in status
- if(!$_SESSION['signed_in'])
- {
- echo 'You must be signed in to post a reply.';
- }
- else
- {
- //a real user posted a real reply
- $sql = "INSERT INTO
- posts(post_content,
- post_date,
- post_topic,
- post_by)
- VALUES ('" . $_POST['reply-content'] . "',
- NOW(),
- " . mysql_real_escape_string($_GET['id']) . ",
- " . $_SESSION['user_id'] . ")";
- $result = mysql_query($sql);
- if(!$result)
- {
- echo 'Your reply has not been saved, please try again later.';
- }
- else
- {
- echo 'Your reply has been saved, check out <a href="topic.php?id=' . htmlentities($_GET['id']) . '">the topic</a>.';
- }
- }
- }
- include 'footer.php';
- ?>
The comments in the code pretty much detail what's happening. We're checking for a real user and then inserting the post into the database.
![]() |
Now that you've finished this tutorial, you should have a much better understanding of what it takes to build a forum. I hope my explanations were clear enough! Thanks again for reading.
Written by: Evert Padje
If you feel useful for you and for everyone, please share it!
Suggest for you:
The Complete PHP with MySQL Developer Course (New)
PHP MySQL Database Connections
Learning PHP 7: From the Basics to Application Development
The Complete PHP 7 Guide for Web Developers
Learn PHP 7 This Way to Rise Above & Beyond Competion!




