how to make a Nested comment-reply using codeigniter and MySQL Database

Codeigniter

Hello everyone,

This article is about how to make a comment-reply system using codeigniter framework and store the comments to mysql database. Here the user can post a comment and other users can reply the post. Nested reply is possible. Other related technologies used are  bootstrap, ajax and jquery.

Please read the article and follow the steps to make nested comment replay.

Step 1: Create database and table

create new database name ‘demos’ on your mysql and create a new table called tbl_comments. and run below sql query to create tbl_comments with all this fields.

CREATE TABLE `tbl_comments` (
 `c_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
 `c_guest_name` varchar(20) NOT NULL,
 `c_guest_mobile` bigint(10) NOT NULL,
 `c_guest_email` varchar(50) NOT NULL ,
 `c_comment` text NOT NULL ,
 `c_parent_id` int(3) NOT NULL ,
 `c_commented_on` timestamp, 
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step 2: Create controller

Create a new file under application/controllers folder, name it as Comment.php. Paste below code on it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 
22 
23
24 
25 
26 
27 
28 
29 
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

<?php defined('BASEPATH') OR exit('No direct script access allowed'); 
class Comment extends CI_Controller { 
        function __construct() {
            parent::__construct(); 
            $this->load->model('CommentModel');
	}
	public function index(){

		$data = array();
		//form-add comment
		if(isset($_POST['add']))
		{	

			$this->form_validation->set_rules('name','Name','required');
			$this->form_validation->set_rules('mobile','Mobile Number',
                        'required|exact_length[10]|numeric');
			$this->form_validation->set_rules('email','Email Address',
                        'required|valid_email');
			$this->form_validation->set_rules('comment','Comment','required');

			if($this->form_validation->run() == TRUE)
			{
				$input = ["c_guest_name" => $_POST['name'],
				"c_guest_mobile" => $_POST['mobile'],
				"c_guest_email" => $_POST['email'],
				"c_comment" => $_POST['comment'],
				];

				$this->CommentModel->insert($input);
				redirect('comment/index');
			}
			
		}
		//form-add comment

		

		//all comments
		$data['comments'] = $this->all_comments();
		
		$this->load->view('v_comment',$data);
	}
	public function all_comments()
	{
		//fetch comment
		$comments = $this->CommentModel->fetch_comments();
		$html_comments = $this->CommentModel->html_comments($comments);
		return $html_comments;
		//fetch comment
	}
	public function reply()
	{

		
	     $this->form_validation->set_rules('name','Name','required');
	     $this->form_validation->set_rules('mobile','Mobile Number','required|exact_
             length[10]|numeric');
	     $this->form_validation->set_rules('email','Email Address','required|valid_
             email');
	     $this->form_validation->set_rules('comment','Comment','required');

			if($this->form_validation->run() == TRUE)
			{
				$input = ["c_guest_name" => $_POST['name'],
				"c_guest_mobile" => $_POST['mobile'],
				"c_guest_email" => $_POST['email'],
				"c_comment" => $_POST['comment'],
				'c_parent_id' => $_POST['parent'],
				];

				$this->CommentModel->insert($input);
				$data['comments'] = $this->all_comments();
				$data['result'] = true;
			}
			else{

				$data['errors'] = validation_errors();
				$data['result'] = false;
			}
			echo json_encode($data);
	}
}

index() function contains the php script to add new comment, call allcomments() function to load all comments and loads the view page. all_comments() function fetch all comments and reply of the comments ie,nested comments. rely() function add the reply of the comment. this function is a ajax request response.

Step 3: Autoload libraries and helpers

Autoload form_validation,database libraries and url helper under autoload.php in config folder.

Step 4: Database connection

 'hostname' => 'localhost', 
'username' => 'root', 
'password' => '',
 'database' => 'demos',

Rewrite hostname,username,password and database name in database.php file from application/config/ directory.

Step 5 : Create Model

Create a new model under models directory of your application. Name it as CommentModel.php and paste below code on it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 
22 
23
24 
25 
26 
27 
28 
29 
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php class CommentModel extends CI_Model { 
     public function fetch_comments($id = null){ 
                $this->db->select('*');
		if(isset($id) && $id != null)
			$this->db->where('c_parent_id',$id);
		else {
			$this->db->where('c_parent_id',0);
			$this->db->order_by('c_commented_on','desc');
		}

		$this->db->from('tbl_comments');
		return $this->db->get()->result_array();
	}
	public function insert($data){
		$this->db->insert('tbl_comments',$data);
		return true;
	}
	public function get_sub_comments($id)
	{

		$sub_comments = $this->fetch_comments($id); 
		if(!empty($sub_comments)){
			$text = '';
			foreach ($sub_comments as $key => $row_sub_comment) {
                             
                           $text   .= '<div class="pl-5 pr-5"> 
                                           <table class="table table-hover">
                                              <tr>
                                                    <td> 
                                                        <p><b>'.$row_sub_comment['c_guest_
                                                         name'].'</b></p> 
                                                        <p style="width: 500px;">'.$row_sub
                                                        _comment['c_comment'].'</p> 
                                                        <h6><a  data-parent= "'. $row_sub_
                                                        comment['c_id'] .'" class="comment_reply
                                                        ">Reply</a> <span class="float-right">
                                                       <small>commented on: '. date('d M, Y h:i
                                                       a', strtotime($row_sub_comment['c_commented
                                                       _on'])).'</small></span></h6> 

                                                        <div id="reply_form'. $row_sub_comm
                                                        ent['c_id'].'" class="reply_form"></div> 
                                                    </td> </tr>';

                           $text   .= '</table>'.$this->get_sub_comments($row_sub_comment
                                      ['c_id']).'
                                       </div>';
                      }
                      return $text;
                }
                else return false;
        } 
        public function html_comments($comments){ 
            if(!empty($comments)){ 
                   $html = ''; 
                   foreach ($comments as $key => $comment_row) {
                        $html  .= '<div class="pl-5 pr-5"> 
                                         <table class="table table-hover">
                                              <tr>
                                                 <td> 
                                                     <p><b>'.$row_sub_comment['c_guest_name
                                                     '].'</b></p> 
                                                     <p style="width: 500px;">'.$row_sub_
                                                     comment['c_comment'].'</p> 
                                                     <h6><a  data-parent= "'. $row_sub_comm
                                                     ent['c_id'] .'" class="comment_reply">
                                                     Reply</a> <span class="float-right">
                                                    <small>commented on: '. date('d M, Y 
                                                    h:i a', strtotime($row_sub_comment
                                                   ['c_commented_on'])).'</small></span></h6> 

                                                     <div id="reply_form'. $row_sub_comment['c_id'].'" 
                                                     class="reply_form"></div> 
                                               </td> </tr>';

                         $html   .= '</table>'.$this->get_sub_comments($row_sub_comment['c_id']).'
                                     </div>'; 
                   }
                   return $html;
            }else return false;
       }
 }   

fetch_comments() function fetch the comments from table. This function is also used to fetch the reply of each comments by passing the parent id of the comment.insert() insert new comment and reply in to table. html_contents() function used to write the comments into html format and get_sub_comments() function fetch the reply’s of each comment.

Step 6: create view

Create a new view page in views directory of your application and paste below code to it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 
22 
23
24 
25 
26 
27 
28 
29 
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

<!DOCTYPE 
<html>
<head> 
<title>Coment Reply</title> 
<!-- Latest compiled and minified CSS --> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap
.min.css">
 <!-- jQuery library --> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <!-- Popper JS --> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js">
</script>
 <!-- Latest compiled JavaScript --> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
 <div class="container"> 
<div class="mt-5">
<h4>Comment Reply using Codeigniter</h4>
</div> 
<div> 
<?php if(validation_errors()) echo "<div class='text-danger'>".validation_errors()."</div>"; ?>
 </div> 
<form method="post" class="mt-5">
 <div class="row"> 
<div class="col-md-12"><h6>New Comment</h6></div> 
<div class="col-md-6"> 
<div class="form-group"> 
<input type="text" name="name"  class="form-control" placeholder="Enter Name"> 
</div> 
<div class="form-group">
 <input type="text" name="mobile"  class="form-control" placeholder="Enter mobile number">
 </div>
 <div class="form-group"> 
<input type="text" name="email"  class="form-control" placeholder="Enter email addres">
 </div> 
</div>
 <div class="col-md-6"> 
<div class="form-group">
<textarea placeholder="Enter your comments here..."  class="form-control" rows="5" 
name="comment"></textarea> 
</div> 
</div> 
<div class="col-md-12">
 <input type="submit" name="add" value="Comment" class="btn btn-block btn-primary">
 </div> 
</div>
 </form>
 <div class="row comments"> 
<div class="pl-3 pr-3"> 
<h3>Comment-Reply</h3>
 <table class="table table-hover ">
 <?php if(!empty($comments)){ echo $comments;} ?> 
</table> 
</div> 
</div> 
</div>

<script type="text/javascript">
 $(document).ready( function() {

$('.comment_reply').click(function(event){ 
$('.reply_form').html(''); 
var cid = $(this).attr('data-parent');
 var content = '<form method="post" id="reply" ><div class="row"><div class="col-md-12">
<h6>New Comment</h6></div><div class="col-md-6"><div class="form-group"><input type="text"
 name="name"  class="form-control" placeholder="Enter Name" ></div><div class="form-group">
<input type="text" name="mobile"  class="form-control" placeholder="Enter mobile number">
</div><div class="form-group"><input type="text" name="email"   class="form-control"
 placeholder="Enter email addres"></div></div><div class="col-md-6"><div class="form-group"
><textarea placeholder="Enter your comments here..."  class="form-control" rows="5" 
name="comment"></textarea></div></div><div class="col-md-12"><input type="hidden" 
name="parent" value="'+cid+'" /><input type="submit" name="reply" value="Reply" 
class="btn btn-block btn-primary"></div></div></form>';
 $('#reply_form'+cid).html(content); }); 
$(document).on('submit','form#reply',function(event){   
event.preventDefault(); 
//alert("Was preventDefault() called: " + event.isDefaultPrevented()); 
var formdata = new FormData($(this)[0]);
 $.ajax({ 
url : "<?= site_url('comment/reply')?>",
 type : 'post',
 data : formdata, 
processData: false, 
contentType: false,
 success: function(response) { 
data = JSON.parse(response); 
if(data.result == true) {
 location.reload();
 } else { 
alert(data.errors); 
} 
}
 }); 
}); 
}); 
</script>
 </body>
</html>

Step 7: Open your application in browser.

Leave a Reply

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