Building a Simple Blog with PHP and MySQL


Creating a blog is an excellent way to learn web development. In this guide, we will build a basic blog using PHP and MySQL, focusing on essential features like creating, reading, updating, and deleting blog posts.


Database Setup

First, you'll need a database to store blog posts. We'll use MySQL for this example. Here's how to set up a MySQL database:

CREATE DATABASE blog_db;
USE blog_db;
CREATE TABLE posts (
 id INT AUTO_INCREMENT PRIMARY KEY,
 title VARCHAR(255) NOT NULL,
 content TEXT NOT NULL,
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Folder Structure

Organize your project with a basic folder structure:

- blog/
 - index.php (Home page showing blog posts)
 - create.php (Form to create a new post)
 - edit.php (Form to edit a post)
 - delete.php (Delete a post)
- includes/
 - db.php (Database connection)
 - functions.php (CRUD functions)

Code Implementation

Create PHP scripts for each functionality. Use HTML forms to input and display data from the database. Here's a simplified example of creating a blog post:

<?php
// db.php - Database connection
$db = new mysqli('localhost', 'username', 'password', 'blog_db');

// create.php - Create a new post
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
 $title = $_POST['title'];
 $content = $_POST['content'];
 $stmt = $db->prepare("INSERT INTO posts (title, content) VALUES (?, ?)");
 $stmt->bind_param('ss', $title, $content);
 $stmt->execute();
 header('Location: index.php');
}
?>

Security Considerations

Basic security practices include input validation to prevent SQL injection, output data escaping to prevent XSS attacks, and using prepared statements for database queries.


Conclusion

You've now built a simple blog with PHP and MySQL. This is a starting point for your web development journey. You can enhance it by adding features like user authentication, categories, and comments as you continue to learn.