Project 2 – Part 2: Create Post (Insert Data)

In this part of Project 2 (CRUD Blog System), we will learn how to insert blog posts into the database using PHP and MySQL.

This is the Create part of CRUD.


What You Will Learn in This Part

  • Create a form to add blog posts
  • Connect PHP with MySQL
  • Insert data into database using mysqli
  • Basic validation
  • Understand real project workflow

Database Table Structure

Make sure you already have a database and table.

Table: posts

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

Step 1: Create Database Connection File

Create a file named db.php

<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "blog_project";

$conn = mysqli_connect($host, $user, $password, $dbname);

if (!$conn) {
    die("Database connection failed: " . mysqli_connect_error());
}
?>

👉 We will reuse this file in all project files.


Step 2: Create Post Form (HTML)

Create a file add-post.php

<!DOCTYPE html>
<html>
<head>
    <title>Add New Post</title>
</head>
<body>

<h2>Add New Blog Post</h2>

<form method="post">
    <label>Post Title:</label><br>
    <input type="text" name="title" required><br><br>

    <label>Post Content:</label><br>
    <textarea name="content" rows="6" required></textarea><br><br>

    <input type="submit" name="submit" value="Add Post">
</form>

</body>
</html>

Step 3: Insert Data Using PHP

Now add PHP code above the HTML in add-post.php

<?php
include "db.php";

if (isset($_POST['submit'])) {
    $title = $_POST['title'];
    $content = $_POST['content'];

    $query = "INSERT INTO posts (title, content) 
              VALUES ('$title', '$content')";

    if (mysqli_query($conn, $query)) {
        echo "<p style='color:green;'>Post added successfully!</p>";
    } else {
        echo "Error: " . mysqli_error($conn);
    }
}
?>

Step 4: Test the Insert Functionality

  1. Open browser
  2. Go to: http://localhost/add-post.php
  3. Enter title and content
  4. Submit the form
  5. Check phpMyAdmin → posts table

🎉 Your post should be inserted successfully.


Important Notes (Beginner Tips)

  • This is basic insertion
  • We will improve security later using:
    • Prepared Statements
    • Validation
    • Sessions

For now, focus on understanding flow.


Common Mistakes

  • Forgetting include db.php
  • Table name mismatch
  • Column name mismatch
  • Not checking database connection

Related Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *