How to develop Projects(BlogApp)
Using PHP and Mysql
Part 12
Module 3: Like / Dislike Feature for Blog Application
🎯 Purpose:
This
module allows users to react to blog posts by either liking or disliking them,
enhancing engagement and providing feedback. It enables toggling between
reactions and displays the like/dislike count for each post.
Functionalities:
1. Like
a Blog Post:
o Users
can express their approval by clicking a "Like" button on a blog
post.
2. Dislike
a Blog Post:
o Users
can express their disapproval by clicking a "Dislike" button on a
blog post.
3. Toggle
Between Like and Dislike:
o Users
who have already reacted to a post can switch between liking or disliking the
post (i.e., they can undo their like and switch to a dislike, or vice versa).
4. View
Like/Dislike Count on Each Post:
o Each
blog post will display the number of likes and dislikes, allowing users to see
the reaction distribution.
Project Structure:
│── /reactions/│ ├── like_dislike.php # Handle like/dislike requests│ ├── reaction_count.php # Get like/dislike count for blog
Database Table:
reactions table:
CREATE TABLE reactions ( id INT AUTO_INCREMENT PRIMARY KEY, blog_id INT NOT NULL, user_id INT NOT NULL, reaction ENUM('like', 'dislike') NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(blog_id, user_id), -- ensures one reaction per user per blog FOREIGN KEY (blog_id) REFERENCES blogs(id) ON DELETE CASCADE, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE);
blog_id: The ID of the blog post the user is reacting to.user_id: The ID of the user who is reacting to the post.reaction: Stores the type of reaction (either "like" or "dislike").created_at: Timestamp of when the reaction was made.- UNIQUE constraint:
Ensures a user can only react once per blog post (either a like or a
dislike).
Code Breakdown:
1. like_dislike.php - Handle Like/Dislike
Requests:
This
file will handle the incoming requests for liking or disliking a blog post. It
will check if the user has already reacted to the post and toggle between the
reactions if necessary.
Example
code:
<?phpsession_start();include('db.php'); // Include the database connection file if(isset($_POST['action']) && isset($_POST['blog_id'])) { $user_id = $_SESSION['user_id']; // Assumed session variable for the logged-in user $blog_id = $_POST['blog_id']; $reaction = $_POST['action']; // Either 'like' or 'dislike' // Check if the user has already reacted to this blog $query = "SELECT * FROM reactions WHERE user_id = ? AND blog_id = ?"; $stmt = $conn->prepare($query); $stmt->bind_param("ii", $user_id, $blog_id); $stmt->execute(); $result = $stmt->get_result(); if($result->num_rows > 0) { // User has already reacted, update their reaction $existing_reaction = $result->fetch_assoc()['reaction']; if($existing_reaction == $reaction) { // If the user is toggling the same reaction, delete their reaction $delete_query = "DELETE FROM reactions WHERE user_id = ? AND blog_id = ?"; $stmt = $conn->prepare($delete_query); $stmt->bind_param("ii", $user_id, $blog_id); $stmt->execute(); } else { // If the user is toggling between like and dislike, update the reaction $update_query = "UPDATE reactions SET reaction = ? WHERE user_id = ? AND blog_id = ?"; $stmt = $conn->prepare($update_query); $stmt->bind_param("sii", $reaction, $user_id, $blog_id); $stmt->execute(); } } else { // If the user has not reacted before, insert the reaction $insert_query = "INSERT INTO reactions (blog_id, user_id, reaction) VALUES (?, ?, ?)"; $stmt = $conn->prepare($insert_query); $stmt->bind_param("iis", $blog_id, $user_id, $reaction); $stmt->execute(); } // Return updated count of likes and dislikes include('reaction_count.php');}?>
2. reaction_count.php - Get Like/Dislike
Count:
This
file will return the current like and dislike counts for a specific blog post.
Example code:
<?phpinclude('db.php'); if(isset($_POST['blog_id'])) { $blog_id = $_POST['blog_id']; // Count likes $like_query = "SELECT COUNT(*) AS like_count FROM reactions WHERE blog_id = ? AND reaction = 'like'"; $stmt = $conn->prepare($like_query); $stmt->bind_param("i", $blog_id); $stmt->execute(); $like_result = $stmt->get_result()->fetch_assoc(); $like_count = $like_result['like_count']; // Count dislikes $dislike_query = "SELECT COUNT(*) AS dislike_count FROM reactions WHERE blog_id = ? AND reaction = 'dislike'"; $stmt = $conn->prepare($dislike_query); $stmt->bind_param("i", $blog_id); $stmt->execute(); $dislike_result = $stmt->get_result()->fetch_assoc(); $dislike_count = $dislike_result['dislike_count']; // Return counts echo json_encode([ 'like_count' => $like_count, 'dislike_count' => $dislike_count ]);}?>
Frontend Example:
You
can have buttons for like/dislike in the blog post view and update the counts
dynamically using AJAX.
html<button class="like-button" onclick="reactToPost('like', blog_id)">Like</button><button class="dislike-button" onclick="reactToPost('dislike', blog_id)">Dislike</button><span id="like-count">0</span> Likes | <span id="dislike-count">0</span> Dislikes
AJAX
Example to Send Like/Dislike Request:
function reactToPost(action, blog_id) { $.ajax({ url: 'reactions/like_dislike.php', method: 'POST', data: { action: action, blog_id: blog_id }, success: function(response) { updateReactionCounts(blog_id); } });} function updateReactionCounts(blog_id) { $.ajax({ url: 'reactions/reaction_count.php', method: 'POST', data: { blog_id: blog_id }, success: function(response) { const data = JSON.parse(response); $('#like-count').text(data.like_count); $('#dislike-count').text(data.dislike_count); } });}
Conclusion:
This module allows users to interact with blog posts by liking or disliking them. It also ensures that a user can only react once per blog post, and they can toggle between like and dislike. Additionally, the system displays the current like and dislike count for each post to improve user engagement.
8️⃣ Blog Application
✅
Module 4: Comment Section
🎯
Purpose:
Allow users to leave comments on blog posts, creating a space for discussion,
feedback, and engagement.
Functionalities:
1. Post
a Comment:
o Users
can write and submit comments on blog posts.
2. View
Comments:
o All
comments related to a particular blog post are displayed beneath the post.
3. Delete
a Comment (if permitted):
o Users
can delete their own comments.
o Admin
can delete any comment.
4. Reply
to Comments:
o Users
can reply to other users' comments, creating a threaded discussion.
5. Comment
Count:
o Display
the total number of comments under each blog post.
Project Structure:
│── /comments/│ ├── post_comment.php # Handle comment posting│ ├── delete_comment.php # Handle comment deletion│ ├── view_comments.php # Retrieve and display comments for a blog post│ ├── reply_comment.php # Handle comment replies│ └── comment_count.php # Get comment count for a blog post
Database Table:
comments table:
CREATE TABLE comments ( id INT AUTO_INCREMENT PRIMARY KEY, blog_id INT NOT NULL, user_id INT NOT NULL, comment TEXT NOT NULL, parent_comment_id INT DEFAULT NULL, -- For replies, references the original comment created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, FOREIGN KEY (blog_id) REFERENCES blogs(id) ON DELETE CASCADE, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (parent_comment_id) REFERENCES comments(id) ON DELETE CASCADE);
blog_id: The ID of the blog post to which the comment belongs.user_id: The ID of the user who posted the comment.comment: The actual comment text.parent_comment_id: For threaded comments, it refers to the ID of the parent comment (if it's a reply).created_at: Timestamp when the comment was posted.updated_at: Timestamp when the comment was last updated.
Code Breakdown:
1. post_comment.php - Handle Comment
Posting:
This
file will allow users to post new comments on blog posts.
Example
Code:
<?phpsession_start();include('db.php'); // Database connection if(isset($_POST['comment']) && isset($_POST['blog_id'])) { $user_id = $_SESSION['user_id']; // Get user ID from session $comment = $_POST['comment']; $blog_id = $_POST['blog_id']; $parent_comment_id = isset($_POST['parent_comment_id']) ? $_POST['parent_comment_id'] : NULL; // Insert the comment into the database $query = "INSERT INTO comments (blog_id, user_id, comment, parent_comment_id) VALUES (?, ?, ?, ?)"; $stmt = $conn->prepare($query); $stmt->bind_param("iisi", $blog_id, $user_id, $comment, $parent_comment_id); $stmt->execute(); // Redirect back to the blog post or return success message header("Location: blog_post.php?id=" . $blog_id); exit;}?>
2. delete_comment.php - Handle Comment
Deletion:
This
file will handle the deletion of comments. It will check if the user is the
author of the comment or if the user is an admin before allowing the deletion.
<?php
session_start();include('db.php'); // Database connection if(isset($_POST['comment_id'])) { $user_id = $_SESSION['user_id']; $comment_id = $_POST['comment_id']; // Check if the user is the owner of the comment or an admin $query = "SELECT * FROM comments WHERE id = ? AND (user_id = ? OR user_id = ?)"; $stmt = $conn->prepare($query); $stmt->bind_param("iii", $comment_id, $user_id, 1); // Assumed 1 is admin ID $stmt->execute(); $result = $stmt->get_result(); if($result->num_rows > 0) { // User is the owner or an admin, delete the comment $delete_query = "DELETE FROM comments WHERE id = ?"; $stmt = $conn->prepare($delete_query); $stmt->bind_param("i", $comment_id); $stmt->execute(); } // Redirect back to the blog post header("Location: blog_post.php?id=" . $_POST['blog_id']); exit;}?>
3. view_comments.php - Retrieve and Display
Comments:
This
file will fetch all the comments for a specific blog post and display them,
including replies to comments.
Example
Code:
<?phpinclude('db.php'); if(isset($_GET['blog_id'])) { $blog_id = $_GET['blog_id']; // Fetch main comments (not replies) $query = "SELECT c.id, c.comment, c.created_at, u.name FROM comments c JOIN users u ON c.user_id = u.id WHERE c.blog_id = ? AND c.parent_comment_id IS NULL ORDER BY c.created_at DESC"; $stmt = $conn->prepare($query); $stmt->bind_param("i", $blog_id); $stmt->execute(); $result = $stmt->get_result(); while($row = $result->fetch_assoc()) { echo "<div class='comment'>"; echo "<p>" . htmlspecialchars($row['comment']) . "</p>"; echo "<small>Posted by " . htmlspecialchars($row['name']) . " on " . $row['created_at'] . "</small>"; // Fetch replies to this comment $parent_comment_id = $row['id']; $reply_query = "SELECT c.comment, c.created_at, u.name FROM comments c JOIN users u ON c.user_id = u.id WHERE c.parent_comment_id = ? ORDER BY c.created_at ASC"; $reply_stmt = $conn->prepare($reply_query); $reply_stmt->bind_param("i", $parent_comment_id); $reply_stmt->execute(); $reply_result = $reply_stmt->get_result(); while($reply = $reply_result->fetch_assoc()) { echo "<div class='reply'>"; echo "<p>" . htmlspecialchars($reply['comment']) . "</p>"; echo "<small>Reply by " . htmlspecialchars($reply['name']) . " on " . $reply['created_at'] . "</small>"; echo "</div>"; } echo "</div>"; }}?>
4. comment_count.php - Get Comment Count:
This
file will return the total number of comments for a specific blog post.
Example
Code:
<?phpinclude('db.php'); if(isset($_POST['blog_id'])) { $blog_id = $_POST['blog_id']; // Get the total comment count $query = "SELECT COUNT(*) AS comment_count FROM comments WHERE blog_id = ?"; $stmt = $conn->prepare($query); $stmt->bind_param("i", $blog_id); $stmt->execute(); $result = $stmt->get_result()->fetch_assoc(); echo json_encode(['comment_count' => $result['comment_count']]);}?>
Frontend Example:
For
the comment section:
<h2>Comments</h2><form action="post_comment.php" method="POST"> <textarea name="comment" required></textarea> <input type="hidden" name="blog_id" value="1"> <!-- Blog ID --> <button type="submit">Post Comment</button></form> <div id="comments-section"> <!-- Comments will be dynamically loaded here via AJAX --></div>
AJAX
to Fetch Comment Count:
function loadCommentCount(blog_id) { $.ajax({ url: 'comments/comment_count.php', method: 'POST', data: { blog_id: blog_id }, success: function(response) { const data = JSON.parse(response); $('#comment-count').text(data.comment_count + ' Comments'); } });}
Conclusion:
This
module adds a comprehensive comment section to your blog application, enabling
users to post comments, reply to others, and interact with the content. It
includes features for viewing and deleting comments and supports a threaded
discussion system. Additionally, it shows a count of the total comments, making
the blog post more interactive.
8️⃣ Blog Application
✅
Module 5: User Authentication and
Authorization
🎯
Purpose:
Implement user authentication and authorization to manage user access, allowing
users to log in, register, and control access based on user roles.
Functionalities:
1. User
Registration:
o Allow
users to register with a username, email, and password.
o Validate
the form and ensure the email is unique.
2. User
Login:
o Provide
login functionality with username/email and password.
o Implement
session management to keep users logged in.
3. User
Logout:
o Enable
users to log out, destroying their session.
4. Role-Based
Access Control (RBAC):
o Users
can have different roles such as "admin," "author," and
"regular."
o Only
admins can access admin features, while regular users can access basic features
like commenting and viewing posts.
5. Password
Reset:
o Allow
users to request a password reset link via email.
o Implement
a secure process for resetting passwords.
6. Profile
Management:
o Users
can update their profiles (name, email, password).
Project Structure:
│── /auth/│ ├── register.php # Handle user registration│ ├── login.php # Handle user login│ ├── logout.php # Handle user logout│ ├── profile.php # Manage user profile│ ├── reset_password.php # Handle password reset request│ ├── update_password.php # Handle password update│ ├── forgot_password.php # Show forgot password form│ └── auth_functions.php # Common functions for authentication
Database Table:
users table:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, email VARCHAR(100) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, role ENUM('admin', 'author', 'regular') DEFAULT 'regular', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);
username: Unique username for the user.email: Unique email for the user (used for login and password reset).password: The hashed password.role: The role assigned to the user (admin, author, or regular).created_at: Timestamp when the user was created.updated_at: Timestamp when the user was last updated.
Code Breakdown:
1. register.php - Handle User Registration:
This
file will allow users to register by submitting their username, email, and
password. The password will be hashed before storing it in the database.
Example
Code:
<?phpinclude('auth_functions.php'); if(isset($_POST['register'])) { $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; if(registerUser($username, $email, $password)) { header("Location: login.php"); exit; } else { echo "Registration failed. Please try again."; }} function registerUser($username, $email, $password) { include('db.php'); // Hash the password $hashed_password = password_hash($password, PASSWORD_BCRYPT); // Insert into the database $query = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)"; $stmt = $conn->prepare($query); $stmt->bind_param("sss", $username, $email, $hashed_password); return $stmt->execute();}?>
2. login.php - Handle User Login:
This
file will handle the login functionality, checking the email and password, and
managing sessions for logged-in users.
Example
Code:
<?phpsession_start();include('auth_functions.php'); if(isset($_POST['login'])) { $email = $_POST['email']; $password = $_POST['password']; if(loginUser($email, $password)) { header("Location: dashboard.php"); exit; } else { echo "Invalid credentials. Please try again."; }} function loginUser($email, $password) { include('db.php'); // Check if user exists in the database $query = "SELECT * FROM users WHERE email = ?"; $stmt = $conn->prepare($query); $stmt->bind_param("s", $email); $stmt->execute(); $result = $stmt->get_result(); if($result->num_rows > 0) { $user = $result->fetch_assoc(); // Verify password if(password_verify($password, $user['password'])) { // Set session variables $_SESSION['user_id'] = $user['id']; $_SESSION['role'] = $user['role']; $_SESSION['username'] = $user['username']; return true; } } return false;}?>
3. logout.php - Handle User Logout:
This
file will log users out by destroying their session.
Example
Code:
<?phpsession_start();session_destroy(); // Destroy sessionheader("Location: login.php"); // Redirect to login pageexit;?>
4. profile.php - Manage User Profile:
This
file will allow users to update their profile information, such as username and
email.
Example
Code:
<?phpsession_start();include('auth_functions.php'); if(isset($_POST['update_profile'])) { $username = $_POST['username']; $email = $_POST['email']; if(updateProfile($_SESSION['user_id'], $username, $email)) { echo "Profile updated successfully!"; } else { echo "Failed to update profile."; }} function updateProfile($user_id, $username, $email) { include('db.php'); $query = "UPDATE users SET username = ?, email = ? WHERE id = ?"; $stmt = $conn->prepare($query); $stmt->bind_param("ssi", $username, $email, $user_id); return $stmt->execute();}?>
5. forgot_password.php - Handle Forgot
Password Form:
This
file will display a form where users can request a password reset by entering
their email.
Example
Code:
<?php// Show the form for email input for password reset?> <form action="reset_password.php" method="POST"> <input type="email" name="email" placeholder="Enter your email" required> <button type="submit">Reset Password</button></form>
6. reset_password.php - Handle Password
Reset:
This
file will process the password reset request, sending an email with a reset
link or token.
Example
Code:
<?php// Handle password reset functionality, including email verification and token generation?>
Frontend Example:
For
login.php:
<h2>Login</h2><form action="login.php" method="POST"> <input type="email" name="email" placeholder="Enter your email" required> <input type="password" name="password" placeholder="Enter your password" required> <button type="submit" name="login">Login</button></form> <a href="forgot_password.php">Forgot Password?</a>
For
register.php:
<h2>Register</h2><form action="register.php" method="POST"> <input type="text" name="username" placeholder="Enter your username" required> <input type="email" name="email" placeholder="Enter your email" required> <input type="password" name="password" placeholder="Enter your password" required> <button type="submit" name="register">Register</button></form>
Conclusion:
This module adds comprehensive user authentication and authorization features to your blog application. It enables users to register, log in, log out, and manage their profiles securely. The password reset functionality is essential for user account recovery, and role-based access control ensures that only authorized users can access certain features. This module improves the security and user experience of your blog application.
8️⃣ Blog Application
✅
Module 6: Commenting System
🎯
Purpose:
Allow users to comment on blog posts, creating more engagement and interaction
within the blog application.
Functionalities:
1. Post
a Comment:
o Logged-in
users can post comments on blog posts.
o Ensure
that each comment is associated with a blog post and the user who posted it.
2. View
Comments:
o Display
all comments under each blog post, showing the username of the commenter and
the time the comment was posted.
3. Edit
Comment:
o Allow
users to edit their comments within a certain time frame after posting.
o Ensure
only the comment's author can edit it.
4. Delete
Comment:
o Allow
users to delete their own comments.
o Admins
can delete any comment.
5. Comment
Moderation (Admin only):
o Admins
can mark comments as spam or inappropriate.
o Admins
can approve or reject pending comments (if moderation is required).
6. Comment
Pagination:
o Paginate
comments to avoid overwhelming the page with too many comments.
Project Structure:
│── /comments/│ ├── post_comment.php # Handle adding new comments│ ├── edit_comment.php # Handle editing comments│ ├── delete_comment.php # Handle deleting comments│ ├── comment_moderation.php # Admin comment moderation│ ├── display_comments.php # Display comments under blog post│ └── comment_functions.php # Common functions for handling comments
Database Table:
comments table:
CREATE TABLE comments ( id INT AUTO_INCREMENT PRIMARY KEY, blog_id INT NOT NULL, user_id INT NOT NULL, comment TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending', FOREIGN KEY (blog_id) REFERENCES blogs(id) ON DELETE CASCADE, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE);
blog_id: The ID of the blog post the comment belongs to.user_id: The ID of the user who posted the comment.comment: The content of the comment.created_at: The timestamp when the comment was created.updated_at: The timestamp when the comment was last updated.status: The status of the comment (pending, approved, or rejected).
Code Breakdown:
1. post_comment.php - Handle Adding New
Comments:
This
file allows logged-in users to post comments on blog posts. Each comment will
be linked to the blog post and the user.
Example
Code:
<?phpsession_start();include('comment_functions.php'); if(isset($_POST['submit_comment'])) { $comment = $_POST['comment']; $blog_id = $_POST['blog_id']; $user_id = $_SESSION['user_id']; if(postComment($user_id, $blog_id, $comment)) { header("Location: view_blog.php?id=$blog_id"); exit; } else { echo "Failed to post comment. Please try again."; }} function postComment($user_id, $blog_id, $comment) { include('db.php'); $query = "INSERT INTO comments (user_id, blog_id, comment) VALUES (?, ?, ?)"; $stmt = $conn->prepare($query); $stmt->bind_param("iis", $user_id, $blog_id, $comment); return $stmt->execute();}?>
2. display_comments.php - Display Comments
for a Blog Post:
This
file retrieves and displays all comments for a particular blog post.
Example
Code:
<?phpinclude('comment_functions.php');$blog_id = $_GET['id']; // Get the blog post ID $comments = getComments($blog_id); foreach($comments as $comment) { echo "<div class='comment'>"; echo "<strong>" . $comment['username'] . "</strong><br>"; echo "<p>" . $comment['comment'] . "</p>"; echo "<small>Posted on " . $comment['created_at'] . "</small><br>"; if ($_SESSION['user_id'] == $comment['user_id']) { echo "<a href='edit_comment.php?id=" . $comment['id'] . "'>Edit</a> | "; echo "<a href='delete_comment.php?id=" . $comment['id'] . "'>Delete</a>"; } echo "</div><hr>";} function getComments($blog_id) { include('db.php'); $query = "SELECT comments.*, users.username FROM comments JOIN users ON comments.user_id = users.id WHERE blog_id = ? AND status = 'approved' ORDER BY created_at DESC"; $stmt = $conn->prepare($query); $stmt->bind_param("i", $blog_id); $stmt->execute(); $result = $stmt->get_result(); return $result->fetch_all(MYSQLI_ASSOC);}?>
3. edit_comment.php - Handle Editing
Comments:
This
file allows users to edit their comments within a time limit or according to
the moderation rules.
Example
Code:
<?phpsession_start();include('comment_functions.php'); $comment_id = $_GET['id'];$comment = getCommentById($comment_id); if($_SESSION['user_id'] != $comment['user_id']) { echo "You can only edit your own comments."; exit;} if(isset($_POST['edit_comment'])) { $new_comment = $_POST['comment']; if(editComment($comment_id, $new_comment)) { header("Location: view_blog.php?id=" . $comment['blog_id']); exit; } else { echo "Failed to edit comment. Please try again."; }} function editComment($comment_id, $new_comment) { include('db.php'); $query = "UPDATE comments SET comment = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?"; $stmt = $conn->prepare($query); $stmt->bind_param("si", $new_comment, $comment_id); return $stmt->execute();} function getCommentById($comment_id) { include('db.php'); $query = "SELECT * FROM comments WHERE id = ?"; $stmt = $conn->prepare($query); $stmt->bind_param("i", $comment_id); $stmt->execute(); $result = $stmt->get_result(); return $result->fetch_assoc();}?>
4. delete_comment.php - Handle Deleting
Comments:
This
file allows users to delete their own comments. Admins can delete any comment.
Example
Code:
<?phpsession_start();include('comment_functions.php'); $comment_id = $_GET['id'];$comment = getCommentById($comment_id); if($_SESSION['user_id'] == $comment['user_id'] || $_SESSION['role'] == 'admin') { if(deleteComment($comment_id)) { header("Location: view_blog.php?id=" . $comment['blog_id']); exit; } else { echo "Failed to delete comment. Please try again."; }} else { echo "You can only delete your own comments.";} function deleteComment($comment_id) { include('db.php'); $query = "DELETE FROM comments WHERE id = ?"; $stmt = $conn->prepare($query); $stmt->bind_param("i", $comment_id); return $stmt->execute();}?>
5. comment_moderation.php (Admin Only) -
Handle Comment Moderation:
This
file allows admins to approve, reject, or mark comments as spam.
Example
Code:
<?phpsession_start();if($_SESSION['role'] != 'admin') { echo "Access denied!"; exit;} include('comment_functions.php'); if(isset($_POST['moderate'])) { $comment_id = $_POST['comment_id']; $status = $_POST['status']; if(moderateComment($comment_id, $status)) { echo "Comment moderated successfully."; } else { echo "Failed to moderate comment."; }} function moderateComment($comment_id, $status) { include('db.php'); $query = "UPDATE comments SET status = ? WHERE id = ?"; $stmt = $conn->prepare($query); $stmt->bind_param("si", $status, $comment_id); return $stmt->execute();}?>
Frontend Example:
For
view_blog.php (where comments
are displayed):
<h2>Comments</h2><form action="post_comment.php" method="POST"> <textarea name="comment" placeholder="Write your comment here..." required></textarea> <input type="hidden" name="blog_id" value="<?php echo $blog_id; ?>"> <button type="submit" name="submit_comment">Post Comment</button></form> <div class="comments"> <?php include('display_comments.php'); ?></div>
