How to develop Projects(BMS) Using PHP and Mysql
Part 9
8️⃣ Blog Application
Module 1: Add / Edit / View Blog
Project Structure:
│── /blogs/
│ ├── add_blog.php # Add blog post
│ ├── edit_blog.php # Edit blog post
│ ├── view_blog.php # View single blog
│ ├── blog_list.php # List all blogs
Database Table:
CREATE TABLE blogs (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
image VARCHAR(255) DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
File: add_blog.php
<?php
session_start();
include 'db.php'; //
Include database connection
// Check if the user is
logged in
if (!isset($_SESSION['user_id']))
{
$_SESSION['error'] = "You must be
logged in to add a blog.";
header("Location: login.php");
exit();
}
// Check if form is
submitted
if ($_SERVER["REQUEST_METHOD"]
== "POST") {
$user_id = $_SESSION['user_id']; // Get
user ID from session
$title = $_POST['title'];
$content = $_POST['content'];
// Handling Image Upload
$image = NULL;
if (!empty($_FILES["image"]["name"]))
{
$target_dir = "uploads/";
$image = $target_dir . basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"],
$image);
}
// Insert data using MySQLi query method
only
$sql = "INSERT INTO blogs (user_id,
title, content, image)
VALUES ($user_id, '$title', '$content',
'$image')";
if (mysqli_query($conn, $sql)) {
$_SESSION['message'] = "Blog added
successfully!";
header("Location: index.php");
exit();
} else {
$_SESSION['error'] = "Error:
" . mysqli_error($conn);
header("Location:
add_blog.php");
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Add Blog</title>
</head>
<body>
<?php
// Display success or
error messages
if (isset($_SESSION['message']))
{
echo "<p style='color:
green;'>" . $_SESSION['message'] . "</p>";
unset($_SESSION['message']);
}
if (isset($_SESSION['error']))
{
echo "<p style='color:
red;'>" . $_SESSION['error'] . "</p>";
unset($_SESSION['error']);
}
?>
<h2>Add New
Blog</h2>
<form action="add_blog.php"
method="POST" enctype="multipart/form-data">
<label>Title:</label><br>
<input type="text" name="title"
required><br><br>
<label>Content:</label><br>
<textarea name="content" rows="5"
required></textarea><br><br>
<label>Image:</label><br>
<input type="file" name="image"><br><br>
<button type="submit">Add
Blog</button>
</form>
</body>
</html>
How It Works
1.
Session Handling
o Ensures
the user is logged in before allowing them to add a blog.
o Redirects
to login.php if not logged in.
2.
Form Handling (POST Method)
o Accepts
title, content, and an optional image.
o Stores
user_id from the session.
3.
Image Upload Handling
o Saves
the uploaded image in the uploads/ directory.
o Stores
the image path in the database.
4.
Inserts Data Using MySQLi Query
o Uses
mysqli_query() to insert the blog.
o On
success, redirects to index.php.
o On
failure, redirects back to add_blog.php with an error message.
5.
Frontend Form
o Displays
error/success messages.
o Contains
an HTML form for adding a blog.
Dependencies
- Ensure
sessions are enabled (session_start()).
- Create
an uploads/ directory to store images.
- Ensure
users table exists and user_id is stored in the session.
File: edit_blog.php
<?php
session_start();
include 'db.php'; //
Include database connection
// Check if the user is
logged in
if (!isset($_SESSION['user_id']))
{
$_SESSION['error'] = "You must be
logged in to edit a blog.";
header("Location: login.php");
exit();
}
// Check if blog ID is
provided
if (!isset($_GET['id']))
{
$_SESSION['error'] = "Invalid
request.";
header("Location: index.php");
exit();
}
$blog_id = $_GET['id'];
$user_id = $_SESSION['user_id'];
// Fetch existing blog
data
$sql = "SELECT *
FROM blogs WHERE id = $blog_id AND user_id = $user_id";
$result = mysqli_query($conn,
$sql);
if (mysqli_num_rows($result)
== 1) {
$blog = mysqli_fetch_assoc($result);
} else {
$_SESSION['error'] = "Blog not found
or you don't have permission to edit it.";
header("Location: index.php");
exit();
}
// Check if form is
submitted
if ($_SERVER["REQUEST_METHOD"]
== "POST") {
$title = $_POST['title'];
$content = $_POST['content'];
//
Handling Image Upload
$image = $blog['image']; // Keep old image
by default
if (!empty($_FILES["image"]["name"]))
{
$target_dir = "uploads/";
$image = $target_dir . basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"],
$image);
}
// Update blog using MySQLi query method
$sql_update = "UPDATE blogs SET title
= '$title', content = '$content', image = '$image' WHERE id = $blog_id AND
user_id = $user_id";
if (mysqli_query($conn, $sql_update)) {
$_SESSION['message'] = "Blog
updated successfully!";
header("Location: index.php");
exit();
} else {
$_SESSION['error'] = "Error:
" . mysqli_error($conn);
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Edit Blog</title>
</head>
<body>
<?php
// Display success or
error messages
if (isset($_SESSION['message']))
{
echo "<p style='color:
green;'>" . $_SESSION['message'] . "</p>";
unset($_SESSION['message']);
}
if (isset($_SESSION['error']))
{
echo "<p style='color:
red;'>" . $_SESSION['error'] . "</p>";
unset($_SESSION['error']);
}
?>
<h2>Edit
Blog</h2>
<form action="edit_blog.php?id=<?php
echo $blog_id; ?>" method="POST" enctype="multipart/form-data">
<label>Title:</label><br>
<input type="text" name="title"
value="<?php echo $blog['title']; ?>"
required><br><br>
<label>Content:</label><br>
<textarea name="content" rows="5"
required><?php echo $blog['content']; ?></textarea><br><br>
<label>Current
Image:</label><br>
<?php if ($blog['image']) { ?>
<img src="<?php echo $blog['image'];
?>" width="100"><br>
<?php } ?>
<label>Change
Image:</label><br>
<input type="file" name="image"><br><br>
<button type="submit">Update
Blog</button>
</form>
</body>
</html>
How It Works
1.
Session Handling
o Ensures
the user is logged in.
o Redirects
to login.php if not logged in.
2.
Fetch Existing Blog Data
o Retrieves
blog details using mysqli_query().
o Ensures
the blog belongs to the logged-in user.
3.
Form Submission
o Updates
the blog title, content, and optionally the image.
o Keeps
the old image if no new file is uploaded.
4.
MySQLi Query Method
o Uses
mysqli_query() to update the record.
5.
Frontend Form
o Displays
existing blog data for editing.
o Shows
the current image with an option to change it.
Dependencies
- db.php
(Database Connection)
- Sessions
enabled (session_start())
- Uploads
folder (uploads/) for images
- User
Authentication (Assumes user_id is stored in
session)
File: view_blog.php
<?php
session_start();
include 'db.php'; //
Include database connection
// Check if blog ID is
provided
if (!isset($_GET['id']))
{
$_SESSION['error'] = "Invalid
request.";
header("Location: index.php");
exit();
}
$blog_id = $_GET['id'];
// Fetch blog details
using MySQLi query method only
$sql = "SELECT
blogs.*, users.name AS author_name FROM blogs
JOIN users ON blogs.user_id = users.id
WHERE blogs.id = $blog_id";
$result = mysqli_query($conn,
$sql);
if (mysqli_num_rows($result)
== 1) {
$blog = mysqli_fetch_assoc($result);
} else {
$_SESSION['error'] = "Blog not
found.";
header("Location: index.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>View Blog</title>
</head>
<body>
<?php
// Display error messages
if any
if (isset($_SESSION['error']))
{
echo "<p style='color:
red;'>" . $_SESSION['error'] . "</p>";
unset($_SESSION['error']);
}
?>
<h2><?php echo $blog['title'];
?></h2>
<p><strong>Author:</strong>
<?php echo $blog['author_name']; ?></p>
<p><strong>Published
on:</strong> <?php echo $blog['created_at']; ?></p>
<hr>
<p><?php echo nl2br($blog['content']);
?></p>
<?php if (!empty($blog['image']))
{ ?>
<img src="<?php echo $blog['image'];
?>" width="300" alt="Blog Image">
<?php } ?>
<br><br>
<a href="index.php">Back
to Home</a>
</body>
</html>
How It Works
1.
Session Handling
o Ensures
valid access and handles errors.
2.
Fetching Blog Data
o Retrieves
blog details using mysqli_query().
o Joins
with users table to fetch the author's name.
3.
Displays Blog Content
o Shows
title, author, creation date, and content.
o Displays
the image if available.
4.
Frontend
o Provides
a clean structure for viewing a blog post.
Dependencies
- db.php
(Database connection)
- Sessions
enabled (session_start())
- Blogs
table with user details
- Uploads
folder for images
File: blog_list.php
<?php
session_start();
include 'db.php'; //
Include database connection
// Fetch all blogs with
author details using MySQLi query method
$sql = "SELECT
blogs.id, blogs.title, blogs.created_at, blogs.image, users.name AS author_name
FROM blogs
JOIN users ON blogs.user_id = users.id
ORDER BY blogs.created_at DESC";
$result = mysqli_query($conn,
$sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Blog List</title>
</head>
<body>
<h2>All
Blogs</h2>
<?php
// Display success or
error messages
if (isset($_SESSION['message']))
{
echo "<p style='color:
green;'>" . $_SESSION['message'] . "</p>";
unset($_SESSION['message']);
}
if (isset($_SESSION['error']))
{
echo "<p style='color:
red;'>" . $_SESSION['error'] . "</p>";
unset($_SESSION['error']);
}
// Check if blogs exist
if (mysqli_num_rows($result)
> 0) {
while ($blog = mysqli_fetch_assoc($result))
{
?>
<div style="border: 1px solid
#ccc; padding: 10px; margin-bottom: 10px;">
<h3><?php echo $blog['title'];
?></h3>
<p><strong>Author:</strong> <?php echo $blog['author_name'];
?></p>
<p><strong>Published
on:</strong> <?php echo $blog['created_at']; ?></p>
<?php if (!empty($blog['image']))
{ ?>
<img src="<?php echo
$blog['image']; ?>" width="150" alt="Blog Image"><br>
<?php } ?>
<a href="view_blog.php?id=<?php
echo $blog['id']; ?>">Read More</a>
</div>
<?php
}
} else {
echo "<p>No blogs
found.</p>";
}
?>
<br>
<a href="add_blog.php">Add
New Blog</a>
</body>
</html>
How It Works
1.
Session Handling
o Displays
success/error messages if any.
2.
Fetching Blog Data
o Retrieves
all blogs with author details using mysqli_query().
o Orders
them by created_at (latest first).
3.
Displays Blog List
o Shows
blog title, author, published date, and image.
o Provides
a "Read More" link to view_blog.php.
4.
Frontend
o Displays
all blogs in a simple list format.
o Provides
a link to add a new blog.
Dependencies
- db.php
(Database connection)
- Sessions
enabled (session_start())
- Blogs
table with user details
- Uploads
folder for images