Comment system in PHP, AJAX, with MYSQL database | source code

Comments are more important for a website. The comment system is used to help readers on the website and readers can ask their questions. Create a comment system in PHP, AJAX, and MYSQL. This is a complete comment and reply system in PHP, AJAX, jQuery, PHP PDO, and MYSQL database. You can download the source code for the comment system in PHP.

How to create a comment system in PHP, AJAX with MYSQL database. 

In this tutorial, you will learn how to create a comment system using PHP, AJAX, and MYSQL database. Here, we will use Bootstrap, jquery, AJAX, and PHP PDO prepared statements. 


First of all, we create two tables – posts and comments. 

CREATE TABLE `comments` (
  `cm_id` int(11) NOT NULL,
  `cm_message` longtext CHARACTER SET utf8 NOT NULL,
  `postid` int(11) DEFAULT NULL,
  `created` datetime NOT NULL,
  `parentid` int(11) NOT NULL,
  `status` tinyint(1) DEFAULT NULL,
  `uname` varchar(40) DEFAULT NULL,
  `uemail` varchar(50) DEFAULT NULL
);
CREATE TABLE `posts` (
  `post_id` int(11) NOT NULL,
  `title` varchar(355) DEFAULT NULL,
  `content` longtext DEFAULT NULL
);


After that, create a connection file. We will create a PHP PDO connection file. 
The connection file is used to make the connection between PHP and to MYSQL database. 
We separate the comment system into two parts. The first part is for comment and the second part is for reply. First of all, display all the posts from the MySQL database. After that, we create a single post page like a blog system in PHP. All comments and replies display below the content on the single post like a blog system.  We create add a comment link to display the comment form. In the comment form, we take three fields – Textarea for comment message, and two textboxes for username and email. 
After that, we create ajax code in the comment_scripts.js file. We call a JS function on click comment button. 

function callCrudAction(action,id) {
     $(".btnAddAction").hide();
  var queryString;
  switch(action) {
    case "add":
    //get closest comment list box
      var selector = $(id).closest(".comment-list-box")
      //get text area and post id values
      var txtmessage = selector.find(".txtmessage").val()
      var postid = selector.find(".postid").val()
        var uname= selector.find(".uname").val()
         var uemail= selector.find(".uemail").val()
      console.log(txtmessage + " --" + postid + " --" + uname + " --" + uemail)
      queryString = 'action=' + action+ '&txtmessage=' + txtmessage+'&postid='+ postid+'&uname='+uname+'&uemail='+uemail;
    break;
    
  }  
  jQuery.ajax({
  url: "comment_action.php",
  data:queryString,
  type: "POST",
  success:function(data){
} 
};


After clicking on the comment button ajax responds and transfers data into another file comment_action.php 

$sql="INSERT INTO comments(cm_message,postid,created,status,uname,uemail,parentid) Values(:cm_message,:postid,:created,:status,:uname,:uemail,:parentid)";
     $stmt = $db->prepare($sql);
       $status=0; 
       $stmt->bindParam(':cm_message', $msg ,PDO::PARAM_STR);
       $stmt->bindParam(':postid', $postid, PDO::PARAM_INT);
           $stmt->bindParam(':parentid', $parentid, PDO::PARAM_INT);
       $stmt->bindParam(':created', $created, PDO::PARAM_STR);
       $stmt->bindParam(':status', $status, PDO::PARAM_INT);
            $stmt->bindParam(':uname', $uname, PDO::PARAM_STR);
             $stmt->bindParam(':uemail', $uemail, PDO::PARAM_STR);
    $stmt->execute();
    $last_id= $db->lastInsertId();
		    if($last_id){
		    	 $sql="SELECT * FROM comments WHERE cm_id=:cm_id"; 
     $stmt = $db->prepare($sql);
        $stmt->bindParam(':cm_id', $last_id, PDO::PARAM_INT);
    $stmt->execute();
        $rows=$stmt->fetchAll(); 
		  foreach($rows as $row)
		  {

if($row["uname"]!=''){$unamo=$row["uname"];} else( $unamo='Anonymous ')
?> 
 
' .$unamo.' '. $row["created"] . '
' . $msg . '
Your comment is awaiting moderation.

'; }?>


On the action file, we insert comment data into the database and display a message to the user “Your comment is awaiting moderation.” using the AJAX success function. 
After that, the admin can moderate comments from the comments.php file. 
Let’s discuss the reply. We call a function reply_form() onlick reply link. We append a reply form with the same textarea and two input boxes. 
When a user clicks on add reply button the ajax response transfer the data on reply_action.php. 
We insert reply data into the database with the parent id and display a message “Your reply is awaiting moderation.”
Admin can moderate and make it live or delete it from the database using the edit and delete button from the comments.php file. 
We created a complete source code for the comment system in PHP. You can easily get download the source code after the process. You will get the complete source code in a zip file. Extract the zip and run your server. The database is also available in the same zip file in the database folder after being extracted. Import the database and edit the config.php file using any text editor. Set your database name and host details. 
Open the index file on your browser and comment on any post. You can moderate comments from the comments.php file. Open comments.php on your browser and edit any comment or reply. You can publish any comment or reply after approval or if you want to make comment or reply private then change the status pending. You can delete comments using the delete button. You can easily download source code for comment systems in PHP, AJAX, and MYSQL. 


Live Chat

Hello! How can we assist you today?