How do I use PHP to create a simple forum?

Creating a Simple Forum with PHP

In this blog post, we will learn how to create a simple forum using PHP and MySQL. A forum is a platform where users can post questions, answers, and engage in discussions. To build our forum, we will create a simple database schema with two tables: one for storing topics and another for storing posts. We will also implement basic CRUD (Create, Read, Update, Delete) operations for both topics and posts.

Let’s start by setting up the database schema.

1. Database Setup:

We will use MySQL as our database. First, create a new database called “simple_forum” and run the following SQL queries to create the required tables:

-- SQL
CREATE TABLE topics (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE posts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    topic_id INT NOT NULL,
    content TEXT NOT NULL,
    author VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (topic_id) REFERENCES topics(id)
);

2. Database Connection:

Create a PHP file named “db.php” to establish a connection with the MySQL database.

<?php
# PHP
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "simple_forum";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

3. Displaying Topics:

Create a PHP file named “topics.php” to display the list of topics.

<?php
# PHP
require_once "db.php";

$sql = "SELECT * FROM topics ORDER BY created_at DESC";
$result = $conn->query($sql);
?>

<!-- HTML -->
<!DOCTYPE html>
<html>
<head>
    <title>Simple Forum</title>
</head>
<body>
    <h1>Topics</h1>
    <a href="create_topic.php">Create a new topic</a>
    <ul>
        <?php while ($row = $result->fetch_assoc()): ?>
            <li>
                <a href="view_topic.php?id=<?= $row['id'] ?>">
                    <?= htmlspecialchars($row['title']) ?>
                </a>
            </li>
        <?php endwhile; ?>
    </ul>
</body>
</html>

4. Creating Topics:

Create a PHP file named “create_topic.php” to add new topics.

<?php
# PHP
require_once "db.php";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = $conn->real_escape_string($_POST["title"]);
    $sql = "INSERT INTO topics (title) VALUES ('$title')";
    
    if ($conn->query($sql) === TRUE) {
        header("Location: topics.php");
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
?>

<!-- HTML -->
<!DOCTYPE html>
<html>
<head>
    <title>Create Topic</title>
</head>
<body>
    <h1>Create a new topic</h1>
    <form method="post" action="create_topic.php">
        <label for="title">Title:</label>
        <input type="text" id="title" name="title" required>
        <button type="submit">Create</button>
    </form>
</body>
</html>

5. Displaying Posts in a Topic:

Create a PHP file named “view_topic.php” to display the posts for a specific topic.

<?php
# PHP
require_once "db.php";

$topic_id = $conn->real_escape_string($_GET["id"]);
$sql_topic = "SELECT * FROM topics WHERE id = '$topic_id'";
$topic = $conn->query($sql_topic)->fetch_assoc();

$sql_posts = "SELECT * FROM posts WHERE topic_id = '$topic_id' ORDER BY created_at ASC";
$posts = $conn->query($sql_posts);
?>

<!-- HTML -->
<!DOCTYPE html>
<html>
<head>
    <title><?= htmlspecialchars($topic['title']) ?> - Simple Forum</title>
</head>
<body>
    <h1><?= htmlspecialchars($topic['title']) ?></h1>
    <a href="topics.php">Back to topics</a>
    <h2>Posts</h2>
    <ul>
        <?php while ($post = $posts->fetch_assoc()): ?>
            <li>
                <p><?= nl2br(htmlspecialchars($post['content'])) ?></p>
                <p><strong>Author:</strong> <?= htmlspecialchars($post['author']) ?></p>
                <p><em>Posted on: <?= $post['created_at'] ?></em></p>
            </li>
        <?php endwhile; ?>
    </ul>
    <h2>Add a new post</h2>
    <form method="post" action="create_post.php">
        <input type="hidden" name="topic_id" value="<?= $topic_id ?>">
        <label for="content">Content:</label>
        <textarea id="content" name="content" required></textarea>
        <br>
        <label for="author">Author:</label>
        <input type="text" id="author" name="author" required>
        <br>
        <button type="submit">Post</button>
    </form>
</body>
</html>

6. Creating Posts:

Create a PHP file named “create_post.php” to add new posts to a topic.

<?php
# PHP
require_once "db.php";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $topic_id = $conn->real_escape_string($_POST["topic_id"]);
    $content = $conn->real_escape_string($_POST["content"]);
    $author = $conn->real_escape_string($_POST["author"]);
    
    $sql = "INSERT INTO posts (topic_id, content, author) VALUES ('$topic_id', '$content', '$author')";
    
    if ($conn->query($sql) === TRUE) {
        header("Location: view_topic.php?id=$topic_id");
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

Now you can start a local web server and visit “topics.php” in your browser to see the simple forum in action. You can create topics, view posts within a topic, and add new posts to a topic.

Note: This simple forum lacks essential features like authentication, input validation, and user-friendly URLs. It is for educational purposes only and not recommended for production use.

Got question?

Submit it here

© All rights reserved.