PHP - Comment System with PHP and MySQL

How to Create a Comment System Using PHP and MySQL Database

How to Create a Comment System Using PHP and MySQL Database


In this PHP project tutorial, we will see how to create a basic comment system using PHP, HTML, CSS, JavaScript, and a MySQL database
The system connects to a MySQL database to store and retrieve comments.
Users can submit comments and replies to specific comments, and there is an option to cancel replies.








Project Source Code:


- Create a Class "db_connect" To Connect Our Form With Database

This file establishes a database connection using PDO (PHP Data Objects) and sets up error handling for the connection.


<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "php-comments";

try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn -> setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo "connection failed: " .$e->getMessage();
die();
}

?>




- On The Comments Page: Creating the HTML Structure

This file contains an HTML form for submitting comments, retrieves and displays comments from a database, allows users to reply to comments, and integrates JavaScript for toggling the display of the reply form.


<!DOCTYPE html>
<html>
<head>
<title>Comment System</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<div class="container">

<form action="operation.php" method="post">
<label for="name"> Name: </label>
<input type="text" name="name" id="name" required>

<label for="comment"> Comment: </label>
<textarea name="comment" id="comment" rows="5" required></textarea>

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

<div class="comments">
<h2>Comments</h2>
<div class="comment-container">
<?php
include 'operation.php';
display_comments($comments);
?>
<!-- test -->
<!-- <ul>
<li class="comment">
<div class="comment-info">
<span class="comment-name">Username</span>
</div>

<div class="comment-text">comment text here</div>
<button class="reply-button">Reply</button>

</li>
</ul> -->

</div>

<form id="reply-form" method="post" action="operation.php">

<input type="hidden" name="parent-id" id="parent-id">
<label for="name">Name:</label>
<input type="text" name="name" id="reply-name">
<input type="hidden" name="reply-to-name" id="reply-to">
<label for="reply-comment-text">Comment:</label>
<textarea name="reply-comment-text" id="reply-comment-text" rows="5" required></textarea>
<button type="submit" name="submit-reply">Submit</button>
<button name="cancel" id="cancel-button">Cancel</button>

</form>


</div>
</div>

<script src="testjs.js"></script>

</body>
</html>



- The Operation File: Handling Form Submissions with PHP

This file manages comment and reply submissions by processing form data, inserting it into the database, and then redirecting to the comments page. 
It also retrieves comments from the database, organizes them hierarchically, and prepares them for display on the web page.


<?php

// Require the database connection file
require_once 'db-connect.php';

// Check if the request method is POST
if($_SERVER['REQUEST_METHOD'] === 'POST'){

// Check if the submit button was clicked
if(isset($_POST['submit'])){

// Check if the name and comment fields are not empty
if(!empty($_POST['name']) && !empty($_POST['comment']))
{
// Get the name and comment values from the form
$name = $_POST['name'];
$comment = $_POST['comment'];
$parent_id = null;

// Prepare an SQL statement to insert the new comment into the database
$stmt = $conn->prepare('INSERT INTO `comments`(`name`, `comment_text`, `parent_id`)
VALUES (:name,:comment,:parent_id)');

// Execute the SQL statement, passing in the name, comment, and parent_id values
$stmt->execute(array(':name'=>$name, ':comment'=>$comment, ':parent_id'=>$parent_id));

// Redirect the user to the comments page after the comment has been added
header('Location: comments.php');
exit;

}
}


if(isset($_POST['submit-reply'])){

$name = filter_input(INPUT_POST,'name',FILTER_SANITIZE_STRING);
$comment_text = filter_input(INPUT_POST,'reply-comment-text',FILTER_SANITIZE_STRING);
$replyTo = filter_input(INPUT_POST,'reply-to-name',FILTER_SANITIZE_STRING);
$comment_text = $replyTo . " " . $comment_text;
$parent_id = $_POST['parent-id'];

// Check if the name and comment fields are not empty
if(!empty($_POST['name']) && !empty($_POST['reply-comment-text']))
{
// Prepare an SQL statement to insert the new comment into the database
$stmt = $conn->prepare('INSERT INTO `comments`(`name`, `comment_text`, `parent_id`)
VALUES (:name,:comment,:parent_id)');

// Execute the SQL statement, passing in the name, comment, and parent_id values
$stmt->execute(array(':name'=>$name, ':comment'=>$comment_text, ':parent_id'=>$parent_id));

// Redirect the user to the comments page after the comment has been added
header('Location: comments.php');
exit;
}

}

}


// Fetch comments
// Select all comments from the database
$stmt = $conn->query('SELECT * FROM `comments`');

// Initialize an empty array to store the comments
$comments = array();

// Loop through each row of the result set and create a comment array
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){

// Create an array to represent the comment
$comment=array(
'id' => $row['id'],
'name' => $row['name'],
'comment' => $row['comment_text'],
'parent_id' => $row['parent_id'],
'replies' => array()
);

// Find parent comment and add this comment as its reply
if($row['parent_id'] !== null)
{
foreach($comments as &$parent){
if($parent['id'] == $row['parent_id']){
$parent['replies'][] = $comment;
}
}
// Remove reference to the last element of $comments
unset($parent);

}else{
// If the comment does not have a parent, add it to the comments array
$comments[] = $comment;
}
}


/**
* This function displays comments in a hierarchical structure.
* @param array $comments An array of comments to display.
* @param int|null $parent_id The ID of the parent comment. If null, display top-level comments.
*/
function display_comments($comments, $parent_id=null){

echo'<ul>';
foreach($comments as $comment){
if($comment['parent_id'] == $parent_id){
// Start displaying the comment
echo'<li class="comment">';
echo'<div class="comment-info">';
echo'<span class="comment-name" data-username="'.$comment['name'].'">'.$comment['name'].'</span>';
echo'</div>';
echo'<div class="comment-text">'.$comment['comment'].'</div>';

// Add reply button
if($parent_id == null){
// Display the reply button for top-level comments
echo'<button class="reply-button"
data-username-text="'.$comment['name'].'"
data-parent-id="'.$comment['id'].'">Reply</button>';
}
else{
// Display the reply button for nested comments
echo'<button class="reply-button"
data-username-text="'.$comment['name'].'"
data-parent-id="'.$comment['parent_id'].'">Reply</button>';
}

// Recursively display replies to the current comment
if(!empty($comment['replies'])){
display_comments($comment['replies'], $comment['id']);
}

// End displaying the comment
echo'</li>';

}
}

echo'</ul>';

}

                                                     

- The testjs.js File: Adding JavaScript for Reply Functionality

this JavaScript file attaches click event listeners to reply buttons, enabling users to reply to comments. When a user selects "Reply," it reveals the reply form, sets the parent comment's ID, and pre-fills the user's name. Additionally, it offers a "Cancel" button for hiding the reply form.


// Get all the reply buttons and assign them to replyButtons variable
const replyButtons = document.querySelectorAll('.reply-button');

// Loop through each reply button and add a click event listener to it
replyButtons.forEach(button => {
button.addEventListener('click', event=>{
// Get the parent ID of the clicked reply button
const parent_id = event.target.getAttribute('data-parent-id');
// Get the username of the user whose comment is being replied to
const name = event.target.getAttribute('data-username-text');
// Set the name input value to '@' + the username
const replyTo = '@'+name;
// Get the reply form and the parent ID field
const replyForm = document.getElementById("reply-form");
const parentField = document.querySelector("#parent-id");
const replyToField = document.querySelector("#reply-to");
replyToField.value = replyTo;
parentField.value = parent_id;

// Show the reply form and scroll to the bottom of the form
replyForm.style.display = "block";
scrollToBottom();

console.log(replyTo);
});
});


// scroll to the bottom to see the reply form
function scrollToBottom(){
const replyForm = document.getElementById("reply-form");
replyForm.scrollIntoView({behavior:"smooth"});
}


// Get the cancel button and the reply form
const cancelButton = document.querySelector("#cancel-button");
const replyForm = document.getElementById("reply-form");

// Add a click event listener to the cancel button
cancelButton.addEventListener('click', event=>{
event.preventDefault();
// Hide the reply form
replyForm.style.display = "none";

});



                                          


////// OUTPUT : 
Comment System with PHP and MySQL


Comment And Reply System with PHP and MySQL


PHP and MySQL Comments And Reply System




if you want the source code click on the download button below















Share this

Related Posts

Previous
Next Post »