How to Build a Comment System in PHP (Step-by-Step)
📌 Thumbnail Text
“Add Comments”
“User Interaction”
“PHP Comment System”
📌 Content
📌 What is a Comment System?
A comment system allows users to:
👉 leave feedback
👉 interact with content
Used in:
blogs
galleries
forums
1️⃣ Create comments table
Run this SQL:
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT,
user_id INT,
comment TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
2️⃣ Create comment form
Inside your post page (gallery.php or view.php):
<form action="comment.php" method="POST">
<input type="hidden" name="post_id" value="<?= $row['id'] ?>">
<textarea name="comment" required></textarea>
<button type="submit">Submit</button>
</form>
3️⃣ Create comment.php
/hosting/foliocraft/html/comment.php
4️⃣ Insert comment (PHP)
<?php
require_once 'db.php';
session_start();
$post_id = $_POST['post_id'];
$user_id = $_SESSION['user_id'];
$comment = $_POST['comment'];
$stmt = $conn->prepare("INSERT INTO comments (post_id, user_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $user_id, $comment);
$stmt->execute();
header("Location: gallery.php");
?>
5️⃣ Display comments
<?php
$stmt = $conn->prepare("
SELECT c.*, u.username
FROM comments c
LEFT JOIN users u ON c.user_id = u.id
WHERE c.post_id = ?
ORDER BY c.id DESC
");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()):
?>
<div>
<strong><?= $row['username'] ?></strong>
<p><?= $row['comment'] ?></p>
<small><?= $row['created_at'] ?></small>
</div>
<?php endwhile; ?>
🔥 Key Features
user comments per post
linked with user account
sorted by latest
🔐 Security Tips
✔ Escape output (important)
<?= htmlspecialchars($row['comment']) ?>
👉 prevents XSS attacks
✔ Validate input
if (empty($comment)) {
die("Comment cannot be empty.");
}
✔ Require login
if (!isset($_SESSION['user_id'])) {
die("Login required.");
}
✨ Optional Features
delete comment
edit comment
reply (nested comments)
like system
✅ Summary
To build a comment system:
create table
create form
insert comment
display comments
add security
🚀 Next Step
You can extend this by:
AJAX comments (no refresh)
pagination
spam filtering
Hope this helps 🚀
Login with Google