Comment and reply system using PHP,AJAX with MYSQL


The comment system is one of the major feature of the website. The comment system is used to help someone. The comment system is placed below the page content like – Blog posts, Products pages, or any website page. In this tutorial, we will learn how to create a comment and reply system using PHP, AJAX, JQUERY, and Bootstrap with the MYSQL database. 

Comment System in PHP and AJAX with MYSQL database – 

In the comment system, we create a textarea with two text boxes to get user data. Users can comment and submit. Comments go to moderation and the admin can make them public after changing the status of the comment from 0 to 1. To create a comment system, we will use AJAX, JQuery framework, Bootstrap framework, PHP PDO prepared statements, and MYSQL database. AJAX is used to perform CRUD operations without page refreshing using PHP. Jquery is the famous JavaScript framework. Bootstrap is also a HTML ,CSS framework. You can create a responsive comment system using bootstrap. We will use PHP PDO prepared statement to create a comment system. PHP PDO with prepared statements will make it more secure without any SQL injection. PHP PDO is also easy to write with easy syntax.

 Comment with reply using PHP – 

In the comment system, we create reply operations also. Users can comment and reply to previous comments. Comments and replies can be approved or deleted by the Admin. 
Let’s create a comment system using PHP and MYSQL database.
First of all, we create database tables. We create two tables. The first table is for posts and the second table for comments. 
Create MYSQL database tables using the queries below.

CREATE TABLE `posts` (
  `post_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(355) DEFAULT NULL,
  `content` longtext DEFAULT NULL
);

All posts will be stored in this table. Users can comment on any post. The post_id column should be auto increment. 
Now, insert some data into the posts table using the query below.

INSERT INTO `posts` (`post_id`, `title`, `content`) VALUES
(1, 'How to create a comment system using PHP with an MYSQL database? Post 1', 'In this tutorial, we create a comment system in PHP. In this tutorial, we create a comment system in PHP'),
(2, 'Comment and reply system in PHP ,AJAX,Jquery and Bootstrap with MYSQL Post 2', 'Comment and reply system in PHP ,AJAX and JQUERY with MYSQL Post 2'),
(3, 'Comment and reply system in PHP and MYSQL', 'The comment system is the most important feature of a website. We will create comment with reply system using PHP, AJAX, Jquery, and Bootstrap with the MYSQL database. '),
(4, 'How to create a comment system in PHP, AJAX, and Jquery, Bootstrap with the MYSQL database?', 'In this tutorial, we will create a comment system using PHP, AJAX, Jquery, and Bootstrap with the MYSQL database. We will use the Jquery Javascript framework, AJax, bootstrap, PHP programming, and MYSQL database. ');

We will use this data and display all posts on the index page and we will create another single post.php page to display the post title, content, and comments. 
Now, create a comments table using the query below. 

CREATE TABLE `comments` (
  `cm_id` int(11) NOT NULL AUTO_INCREMENT,
  `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
);


Make sure the cm_id column should be auto increment. 
Now, we will create a PHP PDO connection file. The connection file is used to connect the page to the MYSQL database. 
config.php 

<?php
define('DBNAME','tute');
define('DBUSER','root');
define('DBPASS','');
define('DBHOST','localhost');
try {
  $db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  //echo "Your page is connected with database successfully..";
} catch(PDOException $e) {
  echo "Issue -> Connection failed: " . $e->getMessage();
}
?>


Kindly set all credentials accurately. 
In the blog system, we display all posts on the index page and display them with post id on another post.php page. Now, we will create an index page. We will display all posts on the index page. 

index.php

<?php require_once("config.php");?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Comment system using AJAX,Jquery,Bootstrap with MYSQL database.</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
	<div div class="row">
<div style="background:grey; color: #fff;" class="card">
	 	<h1>All Posts</h1>	
	</div>
</div>
<br>
    <div class="row">
    	<?php 
      $sql="SELECT * FROM posts ORDER BY post_id DESC"; 
         $stmt=$db->prepare($sql);
            $stmt->execute();
$rows=$stmt->fetchAll();
foreach($rows as $row)
{
	echo '<div class="col-sm-12 list">
 <div class="card"><li><a href="post.php?id='.$row["post_id"].'">'.$row["title"].'</a></li></div>
 </div>'; 
}
    	?> 
    </div>
</div>
</body>
</html>

In the code above, first of all, we included a connection file. We are using bootstrap that’s why linked bootstrap min CSS in the head tag. We fetched and displayed posts using PHP PDO prepared statements. 
Now, we will create a post.php file to display a single post. We will create a comment HTML form below the post title and content. 
Let’s create a post.php file. 

post.php

<?php require_once("config.php");?>
<!DOCTYPE html>
<html>
<?php include("functions.php"); $post_id=$_GET['id']; 
  $sql="SELECT * FROM posts WHERE post_id=:post_id"; 
          $stmt=$db->prepare($sql);
          $stmt->bindParam(':post_id', $post_id ,PDO::PARAM_INT);
              $stmt->execute();
$row=$stmt->fetch();
$title=$row['title']; $content=$row['content']; $post_id=$row['post_id']; 
?>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title><?php echo $title=$row['title'];?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="comment_scripts.js"></script>
<script src="reply_scripts.js"></script>
</head>
<body>
<div class="container">
	<div div class="row">
		<div class="col-sm-12">
	 	<h1><?php echo $title=$row['title'];?></h1>	
	 </div>
</div>
<br>
    <div class="row">
<div class="col-sm-12">
<?php echo $content;?> 
</div>
    </div>
    <br>
    <div class="row">
    	<div class="col-sm-2">
    	</div>
    	<div class="col-sm-8">
    		 <div class="row">
    		<div class="col-sm-12">
    			<!--Comment Column start -->
    			<script type="text/javascript">
    			</script> 		
<hr>
<strong><?php echo count_comment($post_id,$db).' '.name(count_comment($post_id,$db));?> </strong>
<hr>
</div>
</div>
<?php 
$CommentList = commentTree($post_id);
foreach($CommentList as $cl) { ?>
<?php  
if($cl["parentid"]!=0){ 
?>
<!--Reply-->
 <div class="row cm_mainr">
   <div class="col-sm-12 cm_head">
<?php echo ' <div class ="reply_cm"><span class="to-user">@'.userfind($cl["parentid"],$db).'</span> replied by <strong>'.$cl["username"].'</strong> <span class="right">' .easy($cl['created']).'</span><br> </div>'; ?>
</div>
<div class="col-sm-12"> 
<p class="reply"><?php echo $cl["cm_message"].'<br>';  ?> </p>
</div>
</div>
<?php } else {?> 
	<!--Comment-->
	<!--Display Comment & Reply-->
 <div class="row cm_main">
    <div class="col-sm-12 cm_head">
 <div class="cm_author"><?php echo $cl["username"].' <span class="right">' .easy($cl['created']).'</span><br>';?></div>
</div>
 <div class="col-sm-12"> 
<p><?php echo $cl["cm_message"].'<br>';  ?> </p>
</div>
</div>
<?php } ?>
<!--Display Comment & Reply-->
 <!--Append reply form--> 
<div class="row">
  <div class="col-lg-12">
    <div class="comment-list-boxr">
<?php if($cl["parentid"]!=0){ 
    echo '
  <a class="add_comment reply_cm cm_reply" id="reply_'.$cl["cm_id"].'" onclick="reply_form('.$cl["cm_id"].','.$post_id.')"> Reply</a>'; } 
  else 
    { 
echo '
  <span class="cm_reply"><a class="add_comment" id="reply_'.$cl["cm_id"].'" onclick="reply_form('.$cl["cm_id"].','.$post_id.')"> Reply</a></span>';
    } ?> 
   	<div class="reply_area" id="reply_area_<?php echo $cl["cm_id"];?>"></div>
                   <div class="message-wrapcm-<?php echo $cl['cm_id'];?>">    
                    </div>
                </div>
</div>
</div>
 <!--Append reply form-->
<?php } ?>
<hr>
<!--Add New Comment -->
<div class="row">
       <div class="col-sm-12">
        <a class="add_new_comment">Add a comment </a>
       </div>
     </div>
<div class="row">
       <div class="col-sm-12">
  <div class="comment-list-box" >
<div id="frmAdd" class="new_comment_area"> 
  <textarea name="txtmessage" class="txtmessage form-control"  placeholder="Type Comment"  id="ftextarea" cols="auto" rows="2"></textarea>
  <br>
  <div class="row">
      <div class="col-sm-6">
           <input type="text" id="uname" placeholder="Full Name" class="uname form-control" required>
      </div>
       <div class="col-sm-6">
           <input type="email" id="uemail" class="uemail form-control"placeholder="Your Email "  required>
      </div>
  </div>
<input type="hidden" value="<?php echo $post_id; ?>" name="postid" class="postid">
<br><button class="btnAddAction btn btn-primary" name="submit" onClick="callCrudAction('add',this)">Comment </button>
</div>
 <div class="message-wrap">                      
 </div>
</div>
</div>
    	</div>
    	 	<!--Comment Column end -->
    </div>
    	<!--Add New Comment -->
    	<div class="col-sm-2">
    	</div>
    </div>
    </div>
<br> 
<br> <br>
</body>
</html>

As you know, we are creating a comment system using PHP PDO prepared statements, AJAX, JQuery, and bootstrap with the MYSQL database. In the post PHP file, we linked the jquery framework using the script tag. 
You can save it as local and then link jquery or bootstrap. 
First of all, we fetched the post row using id and displayed the title and content. After the content, we started to create comments and reply forms. We will use Ajax to make a response and insert a comment and reply data into the MYSQL database table. 
In the code above, we created various user-defined functions listed below –
count_comment() – Get number of comments included reply – 
name() – If comment count is below 1 then display the title comment (without s) or if greater than 1 then display comments (with s). 
commentTree() – Fetch comment and reply tree using this function.
userfind() – Find parent commenter (Who commented)
These are user-defined functions in PHP. Now, we will create a functions file. All the functions will be found in this file. We already included the functions.php file. 
functions.php 

<?php 
function commentTree($post_id,$parentid = 0, $spacing = '', $user_tree_array = '') {
      global $db;
        if (!is_array($user_tree_array))
    $user_tree_array = array();
$sql = "SELECT comments.cm_message,comments.cm_id,comments.parentid,comments.created,comments.uname
FROM comments WHERE comments.postid=:post_id AND comments.parentid =:parentid AND comments.status=:status ORDER by comments.cm_id DESC";
            $stmt = $db->prepare($sql);
            $status=1;
            $stmt->bindParam(":post_id", $post_id, PDO::PARAM_INT);
              $stmt->bindParam(":parentid", $parentid, PDO::PARAM_INT);
               $stmt->bindParam(":status", $status, PDO::PARAM_INT);
            $stmt->execute();
            //$rows = $stmt->fetchAll();
        $count = $stmt->rowCount();
  if($count> 0) {
    while ($row=$stmt->fetchObject()) {
      $user_tree_array[] = array("cm_id" => $row->cm_id,"parentid" => $row->parentid,"username" => $spacing .$row->uname,"created" => $row->created, "cm_message" => $spacing . $row->cm_message);
      $user_tree_array =commentTree($post_id,$row->cm_id, $spacing , $user_tree_array);
    }
  }
  return $user_tree_array;
}

function easy($date) 
{  
  if($date>0) 
  {
return date('d M Y',strtotime($date));  
}
else
  { 
return ''; 
  }

}
 function userfind($parentid,$db)
{
  $sql = "SELECT cm_message,cm_id,created,parentid,uname FROM comments WHERE cm_id=:cm_id";
            $stmt = $db->prepare($sql);
            $stmt->bindParam(":cm_id", $parentid, PDO::PARAM_STR);
            $stmt->execute();
            $rowcup= $stmt->fetch();
$uname= $rowcup['uname'];
if($uname!='')
{
    return $uname;
}
else{
 return 'Anonymous';
} 
    
}
function count_comment($post_id,$db)
{ 
 $sql= "SELECT count(*) FROM comments WHERE postid=:postid AND status!=0"; 
     $stmt = $db->prepare($sql);
       $stmt->bindParam(':postid', $post_id ,PDO::PARAM_INT);
    $stmt->execute();
        $number_of_rows = $stmt->fetchColumn(); 
        return $number_of_rows;  
}
function name($val)
{ 
if($val<2)
{
  return 'Comment';
}
else 
{
  return 'Comments'; 
}
}
?> 


Now , we will create comment scripts. We cannot complete the comment system without scripts. In the comment scripts, we will create ajax code and jquery code. 
comment_scripts.js 

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){
    switch(action) {
      case "add":
         $(data).insertAfter(".message-wrap:first");
      break;
    }
    $(".txtmessage").val('');
      $(".uname").val('');
        $(".uemail").val('');
      $(".btnAddAction").show();
      $(".new_comment_area").hide();
  },
  error:function (){}
  });
}
 $(document).ready(function(){
  $(".add_new_comment").click(function(){ 
  $(".new_comment_area").show();
   $('#alert').remove();  
  });
});


In the comment script file , we created a callCrudAction() function . We called callCrudAction() in the post.php file . When the user enters the comment message, name, and email and clicks on the comment button, the callCrudAction() function works. We got closest valued of comment-list-box class using closest() function  and sent to comment_action.php file . Comment message(content), username, email, and post id are sent to the comment_action.php file and we will insert these values into the database. 
Now, create a comment action PHP file. 
comment_action.php

<?php require_once("config.php");
 $date = new DateTime(null, new DateTimezone("Asia/Kolkata"));
$created=$date->format('Y-m-d H:i:s');
$action = $_POST["action"];
if(!empty($action)) {
	switch($action) {
		case "add":  
		    
		    if(strlen(trim($_POST["txtmessage"]))<12)  { 
			echo "<div id='alert'><font color='red'>12 characters atleast </font></div>";
			} 
			else {
				$msg=$_POST["txtmessage"];
			$uname=trim($_POST["uname"]);
					$uemail=trim($_POST["uemail"]);
					
        if(strlen($uname)<3){

            $error[] = 'Full Name:Enter atleast 3 charaters.. ';
        } 

          if(strlen($uname)>50){
            $error[] = 'Full Name: Max length 50 Characters Not allowed';
        }
        if($uname!=''){
					if(!preg_match("/^[a-zA-Zs]+$/", $uname)){
            $error[] = 'Full Name:Characters Only (No digits or special charaters) ';
        } 
      }
	         if(!preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,})$/i", $uemail)){
            $error[] = 'Invalid Entry for Email.ie- username@domain.com';
          }
       
         if(strlen($uemail)>100){
            $error[] = 'Email: Max length 100 Characters Not allowed';
            
					}
				
        if(isset($error)){ 
foreach($error as $error){ 
  echo '<p class="alert">'.$error.'</p>'; 
}
 }
  if(!isset($error)){
$postid=$_POST["postid"];
$msg=htmlentities($msg);
$parentid=0;
$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 ')
?> 
 <div class="row cm_main">
    <div class="col-sm-12 cm_head">
				  <?php echo '<div class="message-box"  id="message_' . $last_id. '">
				  <div class="cm_author"><strong>' .$unamo.'</strong> '. $row["created"] . ' </div></div></div>
						<div class="col-sm-12"> 
						<div class="message-content">' . $msg . '</div>
						<div class="alert">Your comment is awaiting moderation.</div>
</div>

	';   }?> 
</div>
					 <?php 
			}
			}
			}
			break;	
			default:		
	}
}
?>


In the comment action, we got Comment message, username, email, and post id values from the ajax response and inserted them into the database. After that, we displayed the “Your comment is awaiting moderation”  message. 
We used PHP PDO Prepared statements to insert data into the database. 
Now, we will create reply scripts same as comment scripts. The reply_scripts.js file will handle reply operations and transfer reply form data to the reply action PHP file same as the comment action PHP file. 
We already created a reply clickable link with every comment. 
reply_scripts.js 

function callCrudActionr(action,id) {
  var queryString;
  switch(action) {
    case "addr":
    //get closest comment list box
      var selector = $(id).closest(".comment-list-boxr")
      //get text area and post id values
      var txtmessager = selector.find(".txtmessager").val()
      var postidr = selector.find(".postidr").val()
       var postm = selector.find(".postm").val()
        var unamer= selector.find(".unamer").val()
         var uemailr= selector.find(".uemailr").val()
      queryString = 'action=' + action+ '&txtmessager=' + txtmessager+'&postidr='+ postidr+'&postm='+ postm+'&unamer='+ unamer+'&uemailr='+ uemailr;
    break;
    
  }  
  jQuery.ajax({
  url: "reply_action.php",
  data:queryString,
  type: "POST",
  success:function(data){
    switch(action) {
      case "addr":
        //selector.append(data);
         $(data).insertAfter(".message-wrapcm-"+ postidr +":first");
      selector.find(".txtmessager").hide()
       selector.find(".unamer").hide()
        selector.find(".uemailr").hide()
       selector.find(".btnAddActionr").hide() 
            selector.find(".btnAddActionclose").hide()
            selector.find(".add_comment").show();
            selector.find(".ap").remove();
      break;
    }
    $(".txtmessager").val('');
  },
  error:function (){}
  });
}
          function reply_form(id,postid)
          {
            $('#reply_area_'+ id ).append('<div class="ap" id="ap_'+id+'"><br><textarea name="txtmessager" class="txtmessager form-control" placeholder="Type reply" id="textarear" cols="auto" rows="2"></textarea><br><div class="row"><div class="col-sm-6"><input type="text" id="unamer" placeholder="Full Name" class="unamer form-control" required></div><div class="col-sm-6"><input type="email" id="uemailr" class="uemailr form-control"placeholder="Your Email "  required></div></div><input type="hidden" value="'+id+'" name="postidr" class="postidr"><input type="hidden" value="'+postid+'" name="postm" class="postm"><br><div class="row"><div class="col-sm-12"><button class="btnAddActionr btn btn-success" name="submit" onClick="callCrudActionr(\'addr\',this))">Add Reply</button> <button class="btnAddActionclose btn btn-warning" name="submit" onClick="closeArea('+id+')">Close </button></div></div><br></div>');
            $('#reply_'+ id ).hide(); 
            $('#alert').remove();  

          }
    
        function closeArea(id)
        {
        $('#ap_'+ id ).remove(); 
          $('#reply_'+ id ).show();   
        }

 

Do you know about the append() function in Javascript? We use the append function to append HTML code, and text with id. We append textarea, name text box, email text box, post text box, and parent comment id text box as hidden using a reply_form(id,postid) function. When the user clicks on the reply link the reply_form(id,postid) works and a form appends to a unique id. We created another function closeArea() that removes appended form on the click close button and also displays a reply link.
In the reply script file, we created a callCrudActionr() function. We called callCrudActionr() from the post.php file . When the user enters the reply message, name, and email and clicks on the add reply button, the callCrudActionr() function works. We got closest valued of comment-list-boxr using closest() function  and sent to reply_action.php file . Reply message, username, email, and post id are sent to the reply_action.php file and we will insert these values into the database. 
reply_action.php

<?php require_once("config.php"); include("functions.php"); 
$date = new DateTime(null, new DateTimezone("Asia/Kolkata"));
$created=$date->format('Y-m-d H:i:s');
$action = $_POST["action"];
if(!empty($action)) {
	switch($action) {
		case "addr":  
		    if(strlen($_POST["txtmessager"])<12)  { 
			echo "<div id='alert'><font color='red'>12 characters atleast </font></alert>";
			} 
			else {
					$msg=$_POST["txtmessager"];
						$uname=trim($_POST["unamer"]);
					$uemail=trim($_POST["uemailr"]);
					if($uname!=''){
					if(!preg_match("/^[a-zA-Zs]+$/", $uname)){
            $error[] = 'Full Name:Characters Only (No digits or special charaters) ';
        } 
      }
        	if(strlen($uname)<3){

            $error[] = 'Full Name:Enter atleast 3 charaters.. ';
        } 

          if(strlen($uname)>50){
            $error[] = 'Full Name: Max length 50 Characters Not allowed';
        }
					
				
         if(!preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,})$/i", $uemail)){
            $error[] = 'Invalid Entry for Email.ie- username@domain.com';
        }
         if(strlen($uemail)>100){
            $error[] = 'Email: Max length 100 Characters Not allowed';
            
					}
					  if(isset($error)){ 
foreach($error as $error){ 
  echo '<p class="alert">'.$error.'</p>'; 
}
 }
					
        if(!isset($error)){ 
   
$postid=$_POST["postm"];
$parentid=$_POST["postidr"];
$status=0;
$msg=htmlentities($msg);
				$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);
       $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 $rowcm)
		  { 
	if($rowcm["uname"]!=''){$unamo=$rowcm["uname"];} else{ $unamo='Anonymous ';}
	?>
 <div class="row cm_main">
    <div class="col-sm-12 cm_head">
<?php 
				  echo '<div class="message-box"  id="message_' . $last_id. '">
				       <div class="reply_cm"> <span class="to-user">@'.userfind($rowcm["parentid"],$db).'</span> replied by <strong>' .$unamo. ' </strong>'. $rowcm["created"] .'</div></div>
				       <div class="col-sm-12">
						<div class="reply_cm">' . $msg. '</div>
							<div class="alert">Your reply is awaiting moderation</div>
</div>

						
						'; } ?> 
</div>
</div>

						<?php 

			}
        }
			}
			break;			
	}
}
?>


In the reply action file, we got reply message, username, email, post id, and parent comment id values from the ajax response and inserted them into the database. After that, we displayed the “Your reply is awaiting moderation”  message. 
Now, users can comment and reply. Comments and replies will be displayed if the status value will be 1. For the test, first of all, comment on any post and reload the page. You will see nothing comment on the page. Go to the database table and change status 0 to 1 then reload the page. Follow the same for the reply. You can perform CRUD operations for comment moderation – like – display comments in the HTML table, edit comments or delete comments or you can send mail notifications using PHPmailer libraries in PHP. 
Now, you can design a comment and reply system using the stylesheet below. 
Create a file style.css.

style.css 


a{
	color: #000000;
	text-decoration: none;
	font-size: 20px; 
}
.list{
	padding-bottom: 10px;
}

.add_comment,.add_new_comment{
 cursor: pointer;  
    color: blue;
}
.new_comment_area{
    display: none;
} 

.fa {
  font-size: 1em;
}

i {

 cursor: pointer; 
}
.reply_cm
{ 

font-size:12px;
 }
 .to-user
 { 
 color: blue;
  }
  .cm_main {
    border: 1px solid #1d9189 !important;

}

   .cm_main{
    border-radius: 10px; 
     }

     .cm_head{ 
      background:#fafafa;
      }
      .cm_author{
        font-size:12px;
      }
      .cm_mainr{
    border: 1px solid #6CF959;
    border-radius: 10px; 
    margin-left:20px !important;
     }
     .cm_reply
     { 
   float: right;
      }
.reply{
  font-size: 14px;
}
.alert{ 
 color: #FF3131;
 font-size: 13px;
 }
 .right {
  float: right;
 }
      .about_author{ 
    font-size:12px;
}
.author{ 
    font-size:14px;
}
.author_username
{ 
 font-size:16px;
 text-decoration: underline;
 }


You can use it as a discussion system with login. for that, you have to create a registration and login system. In this way, you can create a complete comment and reply system using PHP,  MYSQL, AJAX, jQuery, and bootstrap.  


Please Share

Recommended Posts:-