How to Create Comment System with Delete using PHP jQuery

Last modified on November 23rd, 2018 by Vincy.

We have seen many example code for creating comments system using PHP. In this article, we have to implement a PHP comment system with delete option. People used to ask me for integrating comment system into their existing projects. If you are the one among them, this code will give you a preliminary idea to start customizing your own comment system for your application.

Add Comments

In this example code, I have used jQuery AJAX for performing the add or delete comment actions. After performing these actions the dynamic comments list will be updated in the UI without page refresh. If will make the user feel better to look without any jerk on posting or deleting the comments. 

This will be a very useful functionality for many application and sometimes essential too. It is the medium for the user which let them interact with your application. Usually, the comment system contains various features to reply, vote, like/unlike or many other.

Comment System Interface with Delete Option

This code contains the HTML for creating the user interface of the comment system with delete. In this user interface, a HTML form will be displayed to get the user’s name and the comment to be posted.

By posting the comment form data, an AJAX request will be sent to add the user’s comment to the database. Then the UI will be updated by showing the latest comment posted by the user. Also, the total number of comments will be displayed and updated accordingly.

<form action=" " id="frmComment" method="post">
	<div class="row">
		<label> Name: </label> <span id="name-info"></span><input
			class="form-field" id="name" type="text" name="user">
	</div>
	<div class="row">
		<label for="mesg"> Message : <span id="message-info"></span></label>
		<textarea class="form-field" id="message" name="message" rows="4"></textarea>

	</div>
	<div class="row">
		<input type="hidden" name="add" value="post" />
		<button type="submit" name="submit" id="submit"
			class="btn-add-comment">Add Comment</button>
		<img src="LoaderIcon.gif" id="loader" />
	</div>
</form>

Below the comment form, the list of comment data is displayed with a delete option. The delete is a clickable action control which will call the jQuery AJAX delete function on its click event. In a previous tutorial, we have given like or unlike option on each comment item.

<?php
include_once 'db.php';

$sql_sel = "SELECT * FROM tbl_user_comments ORDER BY id DESC";
$result = $conn->query($sql_sel);
$count = $result->num_rows;

if ($count > 0) {
    ?>
<div id="comment-count">
	<span id="count-number"><?php echo $count;?></span> Comment(s)
</div>
<?php } ?>
<div id="response">
<?php
while ($row = $result->fetch_array(MYSQLI_ASSOC)) // using prepared staement
{
    ?>
			<div id="comment-<?php echo $row["id"];?>" class="comment-row">
		<div class="comment-user"><?php echo $row["username"];?></div>
		<div class="comment-msg" id="msgdiv-<?php echo $row["id"];?>"><?php echo $row["message"];?></div>
		<div class="delete" name="delete" id="delete-<?php echo $row["id"];?>"
			onclick="deletecomment(<?php echo $row["id"];?>)">Delete</div>
	</div>
<?php
}
?>
</div>

jQuery Functions to Add Delete Comments

This jQuery script contains functions to add and delete comments depends are on the action request by the users.

On submitting the comment form, the addComment action will be performed via AJAX. Before calling the AJAX script the comment form fields are validated by using jQuery. All the form fields are required to be entered with a value. Once these fields are validated successfully, then the add action will be performed. 

The added comment will be fetched from the database to form the response HTML to update the UI. Each comment row will contain an option to delete that comment.

On clicking the delete of a comment, the JavaScript confirmation box will be shown to the user. Once the user confirms the delete action then the comment-delete.php will be accessed via AJAX to execute the delete query on a particular comment.

<script src="jquery-3.2.1.min.js"></script>
<script type="text/javascript"></script>
<script>

    function deletecomment(id) {

       if(confirm("Are you sure you want to delete this comment?")) {

            $.ajax({
            url: "comment-delete.php",
            type: "POST",
            data: 'comment_id='+id,
            success: function(data){
                if (data)
                {
                    $("#comment-"+id).remove();
                    if($("#count-number").length > 0) {
                        var currentCount = parseInt($("#count-number").text());
                        var newCount = currentCount - 1;
                        $("#count-number").text(newCount)
                    }
                }
            }
           });
        }
     }

	$(document).ready(function() {

        $("#frmComment").on("submit", function(e) {
        		$(".error").text("");
            $('#name-info').removeClass("error");
            $('#message-info').removeClass("error");
            e.preventDefault();
            var name = $('#name').val();
            var message = $('#message').val();
            
            if(name == ""){
            		$('#name-info').addClass("error");
            }
            if(message == ""){
            		$('#message-info').addClass("error");
            }
            $(".error").text("required");
            if(name && message){
                	$("#loader").show();
            		$("#submit").hide();
            	 	$.ajax({
                
                 type:'POST',
                 url: 'comment-add.php',
                 data: $(this).serialize(),
                 success: function(response)
                    {
						$("#frmComment input").val("");
						$("#frmComment textarea").val("");
                     	$('#response').prepend(response);

                         if($("#count-number").length > 0) {
                             var currentCount = parseInt($("#count-number").text());
                             var newCount = currentCount + 1;
                             $("#count-number").text(newCount)
                         }
                         $("#loader").hide();
                 		$("#submit").show();
                     }
                	});
			}
		});
     });
    </script>

PHP Code Accessed via AJAX on Add Delete Comments

In this section, we are going to see the PHP code for the comment-add.php and comment-delete.php. On the form submit event the AJAX script is invoked and access comment-add.php.

In the comment-add.php file, it receives the username and the message posted by the user. Using these parameters, it generates the INSERT query and executes it to add the comment to the database.

After inserting the comment, the recently added comment is retrieved to form the response HTML. The response HTML will contains the row of recently added comment with username, message and the delete option

comment-add.php

<?php
if (isset($_POST['add'])) {
    include_once 'db.php';
    
    $username = $_POST['user'];
    $message = $_POST['message'];
    
    $sql = "INSERT INTO tbl_user_comments (username, message) VALUES ('$username', '$message')";
    $stmt = $conn->prepare($sql);
    
    $stmt->execute();
    $comment_id = $stmt->insert_id;
    ?>
<?php
    
    $sql_sel = "SELECT * FROM tbl_user_comments WHERE id = $comment_id";
    
    $result = $conn->query($sql_sel);
    
    while ($row = $result->fetch_array(MYSQLI_ASSOC)) // using prepared staement
    {
        ?>

<div id="comment-<?php echo $row["id"];?>" class="comment-row">
	<div class="comment-user"><?php echo $row["username"];?></div>
	<div class="comment-msg" id="msgdiv"><?php echo $row["message"];?></div>

	<div class="delete" name="delete" id="delete"
		onclick="deletecomment(<?php echo $row["id"];?>)">Delete</button>

</div>

<?php
    }
}
?>

Similarly, the comment-edit.php is called via jQuery AJAX on the deleteComment() function defined in this example. This function will be called on clicking the delete link that exists on each comment row.

In the comment-delete.php, the comment id is received from the AJAX request parameter list. With the reference of this id, the DELETE will be performed to remove a particular record from the database.

comment-delete.php

<?php
include_once 'db.php';

$comment_id = $_POST['comment_id'];

$sql_del = "DELETE FROM tbl_user_comments WHERE id = $comment_id";
$stmt = $conn->prepare($sql_del);
$stmt->execute();

if (! empty($stmt)) {
    echo true;
}
?>

Database Script for Creating tbl_user_comments Table

The following database script is used to create the tbl_user_comments structure on to your database. Import this script and modify the database configuration in the db.php to run this example in your PHP environment. The same database structure is used for adding comments with emoji but with different collation to store emoji data into the comment field.

--
-- Table structure for table `tbl_user_comments`
--

CREATE TABLE `tbl_user_comments` (
  `id` int(50) NOT NULL,
  `username` varchar(50) NOT NULL,
  `message` varchar(500) NOT NULL,
  `create_at_timestamp` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_user_comments`
--
ALTER TABLE `tbl_user_comments`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_user_comments`
--
ALTER TABLE `tbl_user_comments`
  MODIFY `id` int(50) NOT NULL AUTO_INCREMENT;
COMMIT;

PHP jQuery Create Comment System with Delete Option Output

This screenshot shows the output of this example for creating PHP jQuery comment system with delete feature. This output displays two comments below the comment form. On each comment row, we can see the delete link.

How to Create Comment System with Delete using PHP jQuery

Download

↑ Back to Top

Share this Article