How to Create Comment System with Delete using PHP jQuery

by Vincy. Last modified on July 25th, 2022.

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.

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.

php comments system with delete feature

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.

index.php (landing page HTML form)

<div class="comment-form-container">
    <form action="" id="frmComment" method="post">
        <div class="input-row">
            <div class="label">
                Name: <span id="name-info"></span>
            </div>
            <input class="input-field" id="name" type="text" name="user">
        </div>
        <div class="input-row">
            <div class="label">
                Message: <span id="message-info"></span>
            </div>
            <textarea class="input-field" id="message" name="message"
                rows="4"></textarea>
        </div>
        <div>
            <input type="hidden" name="add" value="post" />
            <button type="submit" name="submit" id="submitButton"
                class="btn-submit">Publish</button>
            <img src="LoaderIcon.gif" id="loader" />
        </div>
    </form>
</div>

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
require_once __DIR__ . '/DataSource.php';
$database = new DataSource();
$sql = "SELECT * from tbl_user_comments ORDER BY id DESC";
$result = $database->select($sql);
?>
<div id="response">
<?php
if (! empty($result)) {
    foreach ($result as $key => $value) {
        ?>
     <div id="comment-<?php echo $result[$key]["id"];?>"
        class="comment-info">
        <div class="outer-comment">
            <div class="comment-info">
                <span class="commet-row-label">from</span> <span
                    class="posted-by"><?php echo $result[$key]["username"];?></span>
                <span class='commet-row-label'>at</span>
				<?php echo $result[$key]["create_at_timestamp"];?>
				</div>
            <div class="comment-text"
                id="msgdiv-<?php echo $result[$key]["id"];?>">
				<?php echo $result[$key]["message"];?></div>
            <div class="delete" name="delete"
                id="delete-<?php echo $result[$key]["id"];?>"
                onclick="deletecomment(<?php echo $result[$key]["id"];?>)">Delete</div>
        </div>
    </div>
<?php
    }
}
?>

It displays the total number of comments with the list of comments posted by the users.

<?php
$count = $database->getRecordCount($sql);
if ($count > 0) {
    ?>
<div id="comment-count">
    <span id="count-number"><?php echo $count;?></span> Comment(s)
</div>
<?php
}
?>

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.

$(document).ready(function() {
	$("#frmComment").on("submit", function(e) {
		e.preventDefault();
		var valid = validate();
		if (valid) {
			$("#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();
				}
			});
		}
	});
});

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.

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)
					}
				}
			}
		});
	}
}

function validate() {
	var name = $('#name').val();
	var message = $('#message').val();
	valid = true;
	$(".error").text("");
	$('#name-info').removeClass("error");
	$('#message-info').removeClass("error");
	if (name == "") {
		$('#name-info').addClass("error");
		valid = false;
	}
	if (message == "") {
		$('#message-info').addClass("error");
		valid = false;
	}
	$(".error").text("required");
	return valid;
}

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
use Phppot\DataSource;
if (isset($_POST['add'])) {
    require_once __DIR__ . '/DataSource.php';
    $database = new DataSource();
    $sql = "INSERT INTO tbl_user_comments (username, message) VALUES (?,?)";
    $paramType = 'ss';
    $paramValue = array(

        $_POST["user"],
        $_POST["message"]
    );
    $lastinsertid = $database->insert($sql, $paramType, $paramValue);

    $sql = "select * from tbl_user_comments where id=? ";
    $paramType = 'i';
    $paramValue = array(
        $lastinsertid
    );

    $result = $database->select($sql, $paramType, $paramValue);

    if (! empty($result)) {
        foreach ($result as $key => $value) {
            ?>
<div id="comment-<?php echo $result[$key]["id"];?>" class="comment-info">
	<div class="outer-comment">
		<div class="comment-info">
			<span class="commet-row-label">from</span> <span class="posted-by"><?php echo $result[$key]["username"];?></span>
			<span class='commet-row-label'>at</span>
		<?php echo $result[$key]["create_at_timestamp"];?>
		</div>
		<div class="comment-text" id="msgdiv"><?php echo $result[$key]["message"];?></div>

		<div class="delete" name="delete" id="delete"
			onclick="deletecomment(<?php echo $result[$key]["id"];?>)">Delete</div>
	</div>
</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
use Phppot\DataSource;
require_once __DIR__ . '/DataSource.php';
$database = new DataSource();
$sql = "DELETE FROM tbl_user_comments WHERE id =? ";
$paramType = "i";
$paramValue = array(
    $_POST["comment_id"]
);
$delete = $database->delete($sql, $paramType, $paramValue);
if (! empty($delete)) {
    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.

--
-- Database: `db_comment`
--

-- --------------------------------------------------------

--
-- 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 DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_user_comments`
--

INSERT INTO `tbl_user_comments` (`id`, `username`, `message`, `create_at_timestamp`) VALUES
(1, 'William', 'Have a Nice Day', '2022-07-14 16:22:46'),
(2, 'Richard', 'Wonderful Experience', '2022-07-14 16:23:43'),
(3, 'Rita', 'Glad to meet you', '2022-07-14 16:24:07');

--
-- 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, AUTO_INCREMENT=400;

Download

Comments to “How to Create Comment System with Delete using PHP jQuery”

Leave a Reply to hboyman96 Cancel reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page