This time we are developing Simple Comment System by using PHP script with Ajax, Jquery, Bootstrap and Mysql Database. If you have seen our how to submit form data by using Ajax JQuery with PHP script without refresh of web page. So we have used same concept here for making Live commenting system by using PHP with Ajax and here comment will be submitted and display on web page without refresh of web page. In short we will make instant comment system without refresh of web page.
In this post we will not discuss simple Comment system in which only single user can submit their comment and nothing but here we have make nested comment system by using PHP code in which if one user has post comment then another user can also reply on that comment and add more review on that comment, and user can reply n level reply. So it will make simple social media system in which they can post their review on particular content. For making nested comment system we have use PHP recursive function which search child comment at n level.
We all know comment or even we can also called review are best way to keep make connection between website content owner and reader of that content. So this script will help you if have use non wordpress site then in that system you can use this type of script for providing user to share their review or feedback regarding your content. Commenting are the best way to exchange ideas for made best website content like article or blog. So for this all reason we have make this Live comment system by using PHP script with Ajax JQuery.
In this post we will not discuss simple Comment system in which only single user can submit their comment and nothing but here we have make nested comment system by using PHP code in which if one user has post comment then another user can also reply on that comment and add more review on that comment, and user can reply n level reply. So it will make simple social media system in which they can post their review on particular content. For making nested comment system we have use PHP recursive function which search child comment at n level.
We all know comment or even we can also called review are best way to keep make connection between website content owner and reader of that content. So this script will help you if have use non wordpress site then in that system you can use this type of script for providing user to share their review or feedback regarding your content. Commenting are the best way to exchange ideas for made best website content like article or blog. So for this all reason we have make this Live comment system by using PHP script with Ajax JQuery.
Source Code
index.php
<?php
//index.php
?>
<!DOCTYPE html>
<html>
<head>
<title>Comment System using PHP and Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<h2 align="center"><a href="#">Comment System using PHP and Ajax</a></h2>
<br />
<div class="container">
<form method="POST" id="comment_form">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
add_comment.php
<?php
//add_comment.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
$error = '';
$comment_name = '';
$comment_content = '';
if(empty($_POST["comment_name"]))
{
$error .= '<p class="text-danger">Name is required</p>';
}
else
{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"]))
{
$error .= '<p class="text-danger">Comment is required</p>';
}
else
{
$comment_content = $_POST["comment_content"];
}
if($error == '')
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>
fetch_comment.php
<?php
//fetch_comment.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($connect, $row["comment_id"]);
}
echo $output;
function get_reply_comment($connect, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
$output .= '
<div class="panel panel-default" style="margin-left:'.$marginleft.'px">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($connect, $row["comment_id"], $marginleft);
}
}
return $output;
}
?>
Database
--
-- Database: `testing`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_comment`
--
CREATE TABLE IF NOT EXISTS `tbl_comment` (
`comment_id` int(11) NOT NULL,
`parent_comment_id` int(11) NOT NULL,
`comment` varchar(200) NOT NULL,
`comment_sender_name` varchar(40) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_comment`
--
ALTER TABLE `tbl_comment`
ADD PRIMARY KEY (`comment_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_comment`
--
ALTER TABLE `tbl_comment`
MODIFY `comment_id` int(11) NOT NULL AUTO_INCREMENT;
Wonderful tutorial. Keep it going and Happy New Year.
ReplyDeleteis the post above same as this commenting system we are using here(below?
Deletehello
Deletegood work please add download button for your source code so that we can easly download great work
DeleteNice post.
ReplyDeleteThanks for your code and for your video tutorial
ReplyDeletehi
ReplyDeletevery helpful
ReplyDeleteThanks
ReplyDeletehow does this work with mobile devices and multiple replies?
ReplyDeleteIt's a dop,,,
ReplyDeletekeeep it up
Abas
ReplyDeletewill this work as a live system
ReplyDeleteno
Deletehsajdhjashdjahsjdasd
ReplyDeleteprettify js how to use please tell me....
ReplyDeletehey! how to i use mysqli because with mysql is giving me error
ReplyDeletenice tutorial, i have a problem i would like to echo the comments only related to a particular post, and not all
ReplyDeleteCheckout my commenting system i built using PHP and AJAX -
ReplyDeletehttps://haymkarran.com/comments.php
Puedes ayudarme con la paginacion de este tutorial
ReplyDeleteThanks for this awesome tutorial! Further on, can you teach us please how to bring down the comment form under a specific comment when we click the reply button?
ReplyDeletenice
ReplyDeletenot working
ReplyDeleteWonderful
ReplyDeleteWonderful
ReplyDeletehow can I replace comment_name by the name of a user who is already logged in?
ReplyDeletehello
ReplyDeletewhat?
ReplyDeletenot showing the results
ReplyDeletethank you very much!!!
ReplyDeleteplease help me how can I change name of database
ReplyDelete1
ReplyDeleteGood one
ReplyDeleteThanks
ReplyDeletesorry...when I click submit nothing happens!! what is the problem?
ReplyDeletethanks
ReplyDeletewhat if we have many other post and we want each post to have its comment
ReplyDeleteThank you Very much;
ReplyDeleteIts working;
Hi I deployed this code but its not working. My hosting company advised me to connect with database like this although:
ReplyDelete$servername = "localhost";
$username = "JMainol";
$password = "xxxxx_";
$databases = "Blog_Dream_Eco_Safari";
$connect = mysqli_connect($servername, $JMainol, $password, $databases);
I dont know where the problem can be
how do i also send post_id to the database
ReplyDeletei want to know as well
DeleteHey, you can do this by capturing the post_id from the page you are displaying your posts. I hope you get what i mean.
Deleteyes
Deletehi
Deletei just started php 11 years old
jgjghjhg
DeleteHi all
Deletehi
ReplyDeletehow can I can set the condition so that the name of the person who is logged is displayed directly as the comment author?
ReplyDeleteHey, you can capture the name of the person using the session id of the user currently logged in.
Deletefollow the steps :
Delete1- login form
2- session condition for sessions start (); is sessions is started and everything is ok then u let the code of form have to be with echo form etc...
3- replace the session varible with the name of input box and let the input box have to be hidden then make a event as onfocus for input comment box "so name input box = session varible "
got it ?
how to send post id and fetch the exact comment which are on a particular post
ReplyDeleteVery helpful. I have integrated this with my code-igniter application and it works perfectly.
Deletei have tried but it not work with code-igniter
Delete;dsqdqs
DeleteHow did you integrate into your application? I have an application, but can't figure out how to add a comment to an existing article.
Deletethank
ReplyDeletekementar
DeleteWhat is i am making a doctor portal and each doctor is given the choice to post an article and this article should be visible on both his and home page for all users.
ReplyDeletewe will tell the webslesson admin to make a section for a users chat for better live question and answers
Deletei have uploaded this script to my domain directory and do some changes also in fetchcomment.php and addcomment.php by changing their database name but its not working
ReplyDeletewats the error plz post the code here
Deletethis is good
Deletesir, when we refresh the page it shows form resubmition error!
ReplyDeletewhat should I do for this
Worked perfect for me, Thanks!
ReplyDeletel lke thi it's work thanks
ReplyDeletehello sir can you add delete function, that would really be great. Thank you.
ReplyDeletenice
ReplyDeleteplease how to Include Add_comment.php and Fecth_comment.php in Index.php
ReplyDeletehola
ReplyDeleteCan you help me out with the newer version of FullCalander Version 4?
ReplyDeleteThere are some different's there and i don't know how i can get it working. Kind regards Pepijn
how to implement it with code-igniter
ReplyDeletegreat! I had been looking for something like that for days - going cracy. Could you, however, give any recommendation on how to use this of different pages? Would be highly appreciated.
ReplyDeleteand could you maybe give an idea about what I just got from you after my last post: "your comment will be .. approval" - how is this to be done?
ReplyDeleteI had a weird effect: I posted to test markup language, , , and tags, the first and last ones work fine, the tag however changed the whole text and not just the enclosing text plus! all prior comments to bold. And I do not like so much that anyone can mess up my whole design. You have any explanation for this? are there more tags that do such stuff, and how to avoid it? Note: before I used this I had substituted the b-tags in the add_comment_php and fetch_command.phh files; also it would be nice, if the number of total comments could be displayed somewhere. I appreciate your efforts, script is very nice apart from the bold thing
ReplyDeletethanks
DeleteA very good script. Thank You.
DeleteThis is the best and simplest tutorial I've ever seen. Well done!
ReplyDeleteadd_comment.php why display the code of error on the webpage
ReplyDeleteCool
ReplyDeleteThank you for this sir, it really helpfull... but how can i connect my post with comments post ???
ReplyDeleteSir wiil you please make a multilevel real time commenting system with laravel ajax.... thanks
ReplyDeleteThank you. Very very thank you for this comment system.
ReplyDeleteWhen I run this code over my local host it works properly but shows 500 error over the real server could anybody please sort out this problem.
ReplyDeleteHi
ReplyDeletethank you so much
ReplyDeleteWould be awesome if you could add toogle replies with ajax.
ReplyDeletewould be awesome if you could add toogle replies with ajax
ReplyDeleteFatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /homepages/29/d775487527/htdocs/comment/fetch_comment.php:5 Stack trace: #0 /homepages/29/d775487527/htdocs/comment/fetch_comment.php(5): PDO->__construct('mysql:host=loca...', 'root', '') #1 {main} Next PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known in /homepages/29/d775487527/htdocs/comment/fetch_comment.php:5 Stack trace: #0 /homepages/29/d775487527/htdocs/comment/fetch_comment.php(5): PDO->__construct('mysql:host=loca...', 'root', '') #1 {main} thrown in /homepages/29/d775487527/htdocs/comment/fetch_comment.php on line 5
ReplyDeletehi
ReplyDeleteIt works, but doesn't add any data to the database.
ReplyDeletehi
ReplyDeleteIt is interesting to see more and more websites and blogs come up with the nested commenting system. It sure is an encouragement to people to comment and communicate causing a better interaction, especially in case of marketing blogs. Keep sharing more views, tips and suggestions about such innovative options in your posts. See more at https://www.metasyssoftware.com/
ReplyDeletesome help plz
ReplyDeleteWarning: PDO::__construct() [pdo.--construct]: [2002] Une tentative de connexion a �chou� car le parti connect� n�a pa (trying to connect via tcp://localhost:3306) in D:\projets\web\infographieClasse\comment\fetch_comment.php on line 5
Fatal error: Maximum execution time of 30 seconds exceeded in D:\projets\web\infographieClasse\comment\fetch_comment.php on line 5
database name testing rakho
DeleteWill this work with index.html instead of index.php?
ReplyDeletethere's an error in fetch_comment line5
ReplyDeleteits not working
ReplyDeletehow can i delete or update my reply sir :o
ReplyDeletehelp please
ReplyDeleteDid this work for somebody once altogether?
ReplyDeletei copy and paste the code but it keep posting double value and also submit value when page is refreshed how to fix that
ReplyDeleteHi there everyone, I have come across almost all the web development sites. However, your website is far better than other in form of content, tools and easiness of using website. Since I am a developer, I am always looking forward to make people aware of web development tools. I can help you people out by introducing you to range of json tools. Here is the link https://jsononline.net/.
ReplyDeleteNice
ReplyDeletevery good article
ReplyDelete
ReplyDeleteFatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetchAll() in C:\xampp\htdocs\comment\fetch_comment.php:21 Stack trace: #0 {main} thrown in C:\xampp\htdocs\comment\fetch_comment.php on line 21
I've done this more than 3 times and it still gives the same error.I think the problem is from the 'fetch_comment.php' file, from the 'fetchAll()' function.
PLEASE I NEED YOUR HELP RIGHT AWAY. Thanks in advance.
very nice post :) Thank You For This Post :-) Keep it up.
ReplyDeleteRandom Number Generator
YTS Torrent Magnet
Lo he probado me ha parecido que esta muy bien son pocos archivos y realmente funciona muy bien, quizás añadiría un sistema de captcha , porque uno de los peores problemas de crear un sistema de comentarios es es el spam
ReplyDeleteIt's not working. Can you do one in procedural for the database part?
ReplyDeletehi had added new two columns of like and unlike i also have added buttons respectively nearby the reply i want to update the database by 1 when users click the like or unlike button can u please guide me with this
ReplyDeleteIt's really helpful tips about comments using php & ajax.
ReplyDeleteHow to use the database, I mean what extension and all to use?
ReplyDeleteThis comment system work properly localhost but not working my godaddy server pse help
ReplyDeletecan u tell me how u create this comment section ?
ReplyDeletehey I am not able to make this system i am not able to sent the message plz help out
ReplyDeleteplz provide to download the source code
ReplyDeleteThanks for sharing such informative post with us regarding creating a comment system in PHP
ReplyDeleteits ok for send ,but i see nothing in the page,its the same of demo,i dont understand
ReplyDeletewhy calendar ist not working
the same probleme ??? why
DeleteHow can we show comments for aspecific page
ReplyDeleteI am really thankful to you because i was thinking that how to make this comment system and when i try every time i stuck on nested reply but i have found the recursive approach in your video. thanks
ReplyDeletethere is a small bug you should work on. Comment can't have two reply because of reply button id
ReplyDeletethanks
This is a very basic starter example and a nice way to demonstrate why nested SQL is not good. Your script works for small pages with a very small amount of comments. I am pretty sure you know that. :)
ReplyDeleteYou can do it better!