Posting comment at the end of the page using PHP MySQL or SQLite

After reading an article on a website, the visitor can post comments or feedbacks at the end.

Database used and table 🔝

We will use MySQL or SQLite database to store the postings of the visitors. Here we are not keeping any site admin table so this script is to be integrated with an existing site admin area. All admin management part is kept inside admin folder.
CREATE TABLE `cmt_post` (
  `post_id` int(5) NOT NULL auto_increment,
  `p_name` varchar(10) NOT NULL,
  `dt` date NOT NULL,
  `name` varchar(25) NOT NULL,
  `email` varchar(50) NOT NULL,
  `dtl` text NOT NULL,
  `status` varchar(4) NOT NULL default 'ns',
  UNIQUE KEY `post_id` (`post_id`,`p_name`)
CREATE TABLE `cmt_post` (
  `post_id` integer primary key,
  `p_name` text,
  `dt` text,
  `name` text,
  `email` text,
  `dtl` text,
  `status` text default 'ns'

Integration of script with different Posts 🔝

Towards the end of each page or post we will keep this code to call different pages of the script. Note that we have one variable $p_name which is to be assigned a unique string to identify the page.
//////// start of comment /////////////
$p_name="1be"; // Unique file name of the page. 
require "config.php"; //Remove if  already have db connection
require "cmt-display.php"; // To display the comments
require "cmt-formck.php"; // Processing the form data
require "cmt-form.php"; // To display the form.
/////// end of comment //////////////

Displaying the comments posted by users cmt-display.php 🔝

It uses the unique page name p_name and collects all the records. Inside the WHERE clause of sql query we have restricted the records which are not approved by the site admin by adding status='apv'.
SELECT name,dtl,dt FROM cmt_post WHERE p_name=:p_name AND status='apv' ORDER BY dt
Finally we will display them in the order of date of post column dt. While displaying we will convert the date filed value to readable format by using strtotime function. Here is the complete code for displaying the postings.
//require 'config.php'; // remove if database connection is already there
$query="SELECT name,dtl,dt FROM cmt_post WHERE p_name=:p_name and status='apv' ORDER BY dt";

$step = $my_conn->prepare($query);
$step->bindParam(':p_name', $p_name,PDO::PARAM_STR,10);
$step = $step->fetchAll();

echo "<table width='400' border='0' cellspacing='1' cellpadding='0'>";
foreach($step as $row){$dtl=nl2br($row['dtl']);
echo "<tr bgcolor='#f1f1f1'><td>$row[name]</td>
	<td align=right>".date("d-m-Y",strtotime($row['dt']))."</td></tr>";
echo "<tr ><td colspan=2>$dtl</td></tr>";
echo "</table>";

Posting of comments: showing the form by cmt-form.php 🔝

We will ask the visitors to enter three fields at the posting form. One is there name, second one is their email address and third one is there comment or feedback. Here while displaying we will not display the email address of the poster and we will only display name and the posted comment.

The file cmt-form.php will show the posting form to the user to enter the details.
echo "<table width='400' border='0' cellspacing='1' cellpadding='0'>
<form method=post action=''><input type=hidden name=todo value=post_comment>
<tr bgcolor='#f1f1f1'><td>Name</td><td><input type=text name=name></td></tr>
<tr ><td>Email</td><td><input type=text name=email>( not to be displayed)</td></tr>
<tr bgcolor='#f1f1f1'><td colspan=2>
<textarea name=dtl rows=3 cols=50></textarea>
<tr ><td colspan=2 align=center><input type=submit value='Post Comment'></td></tr>
Once the details are submitted the data is posted to cmt-formck.php page.

Storing the posted comment in database table cmt-formck.php 🔝

This main cmt_post table will have fields to store the name, email address, date of post and comment. It also has to store the unique page number or page name by which we can identify which comment or posting belongs to which page. We will maintain one more column status which will indicate the posting is approved by site admin or not. By default all posting are to be approved by site admin. We will maintain this status filled with two values, ns(not seen) or fresh posting and second value is apv( approved ) . For each record once added we will generate one unique post id ( post_id) . For this post_id column we will use auto increment property of MySQL table.
if(isset($todo) and $todo=="post_comment"){

$name=$_POST['name']; // Collect name as entered by user 

$status = "OK"; // flag for input validation

// if name  is less than 3 char then status is not ok
if( strlen($name) <3 or strlen($name) > 25){
$msg=$msg."Your Name  should be more than 2 and less than25 char length<BR>";
$status= "NOTOK";}					

if( strlen($dtl) <3 ){
$msg=$msg."Your comment should be more than 3 char length<BR>";
$status= "NOTOK";}					

if($status<>"OK"){ // validation failed
echo "<font face='Verdana' size='2' color=red>$msg</font>";
}else{ // if all validations are passed.
$status='ns'; //Change this to apv if you want all messages to be automatically approved once posted.

$query="INSERT INTO cmt_post(p_name,dt,name,email,dtl,status)
$step->bindParam(':p_name',$p_name,PDO::PARAM_STR, 10);
$step->bindParam(':name',$name,PDO::PARAM_STR, 15);

echo " <font face='Verdana' size='2' color=green>Thank you for posting your comment<br></font>";
echo " Not able to add data please contact Admin ";
} // 
} // if status is ok 
}// Checking of if condition if form is submittted

Admin : Admin Area to mangage comments posted 🔝

Inside the admin area site admin after login ( Login process is not included in this script ) can view the all the comments or only list the comments which are in ns status ( not seen ). While viewing the list site admin can see name, email date of post etc along with status of the posting. Admin can click the link Details and see full details of the post. Here admin can change the status to apv ( approved ) or can delete the post. Here any approved posting ( status = apv) can be changed to not seen ( status = ns ).

In list.php page all the records ( or posts ) get listed in the order of date of post. If required admin can go to a page where not approved ( status =ns) records are only displayed. Here is the code for list.php page, a simple collection of records from the table.
$query="SELECT * FROM cmt_post order by dt ";

echo "<table width='100%' border='0' cellspacing='1' cellpadding='0'>";
foreach($my_conn->query($query) as $row){
echo "<tr bgcolor='#f1f1f1'><td><b>id</b>:$row[post_id] <b>name</b>:$row[name] 
 <b>email</b>:$row[email] <b>status</b>:$row[status] <a href='list-dtl.php?post_id=$row[post_id]&f_name=list.php'>Details</a></td>
 <td align=right>".date("d-m-Y",strtotime($row['dt']))."</td></tr>
 <tr ><td colspan=2>$row[dtl]</td></tr>";
echo "</table>";

Admin: Displaying details and updating status 🔝

By using the post_id all details of the record is displayed with radio buttons to change the status.
$query="select * from cmt_post where post_id=:post_id";

echo " Success <br>";
$row = $count->fetch(PDO::FETCH_OBJ);

echo "<table width='100%' border='0' cellspacing='1' cellpadding='0'>";
echo "<tr bgcolor='#f1f1f1'><td><b>id</b>:$row->post_id <b>name</b>:$row->name 
<b>email</b>:$row->email <b>status</b>:$row->status</td>
<td align=right>".date("d-m-Y",strtotime($row->dt))."</td></tr>";
echo "<tr ><td colspan=2>$row->dtl</td></tr>";
echo "</table>";
echo "<hr>";
Once the admin submit the form for change of status the form data goes to list-dtlck.php page. Here all the form data collected and first checked if delete options is selected. Record is deleted if delete option is given or the status is changed as per the selection. After the changes the page automatically redirect to list.php page with a message displayed at the top of the list.php page. Here is the code.


$query="DELETE FROM cmt_post WHERE post_id=:post_id";
if($step->rowCount() <> 1){
header ("Location: $f_name?msg=<br>Not able to delete Record "); 
}else{header ("Location: $f_name?msg=<br>Record  deleted "); }

$query="UPDATE cmt_post SET status='$status' WHERE post_id=:post_id";
if($step->rowCount() <> 1){
header ("Location: $f_name?msg=<br>Not able to update Record"); 
}else{header ("Location: $f_name?msg=<br>Record updated "); }
}// end of todo checking
header ("Location: $f_name?msg=<br>Data Problem"); 

Using SQLite or MySQL 🔝

Open dump-mysql.sql file and use the query to create cmt_post table in MySQL database.
Open dump-sqlite.sql file and use the query to create cmt_post table in SQLite database in your SQLite3.
Or use sqlite_create_table.php file to create cmt_post after updating config.php file.

Open config.php and use the section as marked based on your database selection.
#### FOR SQLite Database ######
// This will create the database if not exists in the same location where the script is running.
// For a different location give the path details. 
//$my_conn = new PDO('sqlite:D:\\sqlite-data\\student.db');// different path
$my_conn = new PDO('sqlite:'.dirname(__FILE__).'/comment.db'); // same location
#### end of SQLite database connection #####

###### PHP PDO with MySQL ##### For php PDO use below lines ##
$host_name = "localhost"; // or different host 
$database = "my_db";   // Change your database name
$username = "root";    // Your database user id 
$password = "password";// Your password

//////// Do not Edit below /////////
try {
$my_conn = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
####### END of PHP PDO ######

Download the script with Database details 🔝


Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net



    Yea um, I am keep getting a error saying: Warning: mysql_connect(): Can't connect to local MySQL server through socket '/usr/local/mysql-5.0/data/mysql.sock' (2) in /home/content/d/r/a/dragonlover/html/ funtut/comment/comment/config.php on line 19 Could not connect to MySQL


    You have to check your mysql connection first. You should have correct userid and password to connect to Mysql table. There is a tutorial on this issue. First establish connection and then your script will work.


    test comment


    Hi there i can't login in the admin page every time i try to login it says wrong password. And i dont even know how to make admin name and password please help on how to accecc admin.. and the other thing is how to add the script into everypage in my website. thanks alot


    Go to page on installing comment posting script. It is there in further reading section. There default id and how it works is explained.


    thanks for this php tutorial


    Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\AppServ\www\comment \cmt-display.php on line 2 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:\AppServ\www\comment \cmt-display.php on line 2 Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\comment\ cmt-display.php on line 5


    Warning: mysql_connect(): Can\'t connect to local MySQL server through socket '/usr/local/mysql-5.0/data/ mysql.sock' (2) in /home/content/d/r/a/dragonlover/html/ funtut/comment/comment/config.php on line 19 Could not connect to MySQL.


    why wont this work
    john doe


    ajax feature is very cool.


    let me test


    Can somebody help me i dont anderstand whats the problem: Warning: mysql_query() [function.mysql-query]: Access denied for user 'watching'@'localhost' (using password: NO) in /home/watching/public_html/comment/cmt-display.php on line 2 Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/watching/public_html/comment/cmt-display.php on line 2 Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/watching/public_html/comment/cmt-display.php on line 5


    at the end. You must have seen such comments at blog pages posted by visitors are displayed at the end of the page. Below such postings there will be the form which you can use and post your comments. Such a provision adds lot of value to the main content as replies and questions are both available at one place. Author of the article can post answer to specific questions raised by readers. Over time this system itself became a FAQ ( frequently asked questions ) page as over the subject lot of discussion became available at one place. Blog pages are somewhat similar to this script. This script can be further extended to


    i am tesing this comments blogs


    Is the tutorial and download for the script is same as the one i am now posting comments on your site?
    Jack Frost


    really good site and always with good scripts...thanks


    James, this is not the same script. Some changes are added and it is based on Ajax. The tutorial is not yet developed and download link is not kept. Shortly it will be available.
    Paltonio Fraga


    very useful programs. Thanks for this. Even not using a mysql database, we can use any/another source of data.


    yup not too bad but i wanna how to connect mysql with ajax


    How to post a comment and the page not reload?


    By using Ajax.


    this site is great!!!!!!!!!
    Andy John


    Excellent post.This was actually what I was looking for, and I am glad that I finally came here! Thanks for sharing the such information with us.


    When will the ajax feature be ready for download? Another thing here is this. I tried using this script to add comments to the cms tutorial here but it keeps displaying the same comment for all articles. I guess the $p_name=1be is responsible. How can i make it dynamic just like the cms so i can have different comments on different pages. Please admin, note i'm working with the cms file from this website.


    This is good. Just some adjustment i changed require"....php" to include"...php" and i was able to log in. i am using dynamic php web pages so i changed $p_name = $_GET['mytopicid']; so that a comment for a page is not onto another. I am a php newbie and very chuffed i did this on my own.


    You have to check your mysql connection first. You should have correct userid and password to connect to Mysql table. There is a tutorial on this issue. First establish connection and then your script will work.


    Is there any demo for this script


    Your post is incredible, can’t wait for more updates


    Thankyou this script is quite nice and easy to work with


    Is there one without MY SQL


    is there 1 with sql???




    Nice one


    new post
    Jordan Rusnac


    heya this is the one im looking for


    Is this using databse?


    thank for helpful script


    Is this using databse?

    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer