Creating a Blog Module with Categories in PHP involves a few steps.

Creating a Blog Module with Categories in PHP involves a few steps. Here's a simplified approach:

1. Database Structure

You'll need a database with two main tables:

  1. blog_categories: To store blog categories.
  2. blog_posts: To store the blog posts.

Table Structures:

categories table:

CREATE TABLE blog_categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

posts table:

CREATE TABLE blog_posts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    category_id INT NOT NULL,
    title VARCHAR(255) NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (category_id) REFERENCES categories(id)
);

2. Backend PHP Code

Database Connection

Create a db.php file for the database connection:

<?php
$host = 'localhost';
$db = 'blog_db';
$user = 'root';
$pass = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}
?>

Fetch Categories and Posts

Fetch categories:

<?php
require 'db.php';

$stmt = $pdo->prepare("SELECT * FROM categories");
$stmt->execute();
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

Fetch posts by category:

<?php
require 'db.php';

$categoryId = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 0;

if ($categoryId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM posts WHERE category_id = :category_id");
    $stmt->bindParam(':category_id', $categoryId, PDO::PARAM_INT);
    $stmt->execute();
    $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    $posts = [];
}
?>

3. Frontend Display

Category Links

<ul>
    <?php foreach ($categories as $category): ?>
        <li>
            <a href="blog.php?category_id=<?= $category['id'] ?>">
                <?= htmlspecialchars($category['name']) ?>
            </a>
        </li>
    <?php endforeach; ?>
</ul>

Posts Display

<div>
    <?php if (!empty($posts)): ?>
        <?php foreach ($posts as $post): ?>
            <h2><?= htmlspecialchars($post['title']) ?></h2>
            <p><?= nl2br(htmlspecialchars($post['content'])) ?></p>
            <hr>
        <?php endforeach; ?>
    <?php else: ?>
        <p>No posts available for this category.</p>
    <?php endif; ?>
</div>

4. Adding a New Post

Create a form to add new posts.

HTML Form

<form action="add_post.php" method="post">
    <label for="category">Category:</label>
    <select name="category_id" id="category">
        <?php foreach ($categories as $category): ?>
            <option value="<?= $category['id'] ?>"><?= htmlspecialchars($category['name']) ?></option>
        <?php endforeach; ?>
    </select>
    
    <label for="title">Title:</label>
    <input type="text" id="title" name="title" required>
    
    <label for="content">Content:</label>
    <textarea id="content" name="content" required></textarea>
    
    <button type="submit">Add Post</button>
</form>

PHP to Handle the Form Submission

add_post.php:

<?php
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $categoryId = $_POST['category_id'];
    $title = $_POST['title'];
    $content = $_POST['content'];

    $stmt = $pdo->prepare("INSERT INTO posts (category_id, title, content) VALUES (:category_id, :title, :content)");
    $stmt->bindParam(':category_id', $categoryId, PDO::PARAM_INT);
    $stmt->bindParam(':title', $title, PDO::PARAM_STR);
    $stmt->bindParam(':content', $content, PDO::PARAM_STR);

    if ($stmt->execute()) {
        echo "Post added successfully!";
    } else {
        echo "Failed to add the post.";
    }
}
?>

5. Additional Features

  • Add pagination for posts.
  • Create a search functionality.
  • Style with CSS or integrate a frontend framework like Bootstrap.

This modular approach ensures that your blog is easy to maintain and expand.

Did you find this article useful?