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`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
SQLite
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.
<?Php
//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->execute();
$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.
<?Php
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>
</td></tr>
<tr ><td colspan=2 align=center><input type=submit value='Post Comment'></td></tr>
</table></form>
";
?>
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.
<?Php
@$todo=$_POST['todo'];
if(isset($todo) and $todo=="post_comment"){

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

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

// 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.
$dt=date("Y-m-d"); 
$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)
 values(:p_name,'$dt',:name,:email,:dtl,'$status')";
$step=$my_conn->prepare($query);
$step->bindParam(':p_name',$p_name,PDO::PARAM_STR, 10);
$step->bindParam(':name',$name,PDO::PARAM_STR, 15);
$step->bindParam(':email',$email,PDO::PARAM_STR,50);
$step->bindParam(':dtl',$dtl,PDO::PARAM_STR);

if($step->execute()){
$mem_id=$my_conn->lastInsertId(); 
echo " <font face='Verdana' size='2' color=green>Thank you for posting your comment<br></font>";
}
else{
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.
$post_id=$_GET['post_id'];
$f_name=$_GET['f_name'];
$query="select * from cmt_post where post_id=:post_id";
$count=$my_conn->prepare($query);
$count->bindParam(":post_id",$post_id,PDO::PARAM_INT,3);

if($count->execute()){
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>";
}else{
//$row=$count->fetchAll();
print_r($dbo->errorInfo()); 
}
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.
@$todo=$_POST['todo'];

if($todo=="status-up"){
$f_name=$_POST['f_name'];
$post_id=$_POST['post_id'];
$status=$_POST['status'];


if($status=="del"){
$query="DELETE FROM cmt_post WHERE post_id=:post_id";
$step=$my_conn->prepare($query);
$step->bindParam(":post_id",$post_id,PDO::PARAM_INT,3);
$step->execute();
if($step->rowCount() <> 1){
header ("Location: $f_name?msg=<br>Not able to delete Record "); 
}else{header ("Location: $f_name?msg=<br>Record  deleted "); }

}else{
$query="UPDATE cmt_post SET status='$status' WHERE post_id=:post_id";
$step=$my_conn->prepare($query);
$step->bindParam(":post_id",$post_id,PDO::PARAM_INT,3);
$step->execute();
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
else{
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.
<?Php
#### 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
$my_conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
#### 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/>";
die();
}
*/
####### END of PHP PDO ######
?>

Download the script with Database details 🔝


Scripts

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Joe

    24-01-2009

    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
    smo

    25-01-2009

    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.
    asdas

    17-02-2009

    test comment
    Haji

    22-02-2009

    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
    smo

    22-02-2009

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

    03-03-2009

    thanks for this php tutorial
    moles

    03-03-2009

    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
    asd

    10-04-2009

    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.
    sasa

    18-04-2009

    why wont this work
    john doe

    06-05-2009

    ajax feature is very cool.
    james

    15-05-2009

    let me test
    winstons

    21-06-2009

    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
    333

    29-06-2009

    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
    sajjad

    01-07-2009

    i am tesing this comments blogs
    james

    31-07-2009

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

    31-07-2009

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

    02-08-2009

    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

    12-08-2009

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

    23-08-2009

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

    02-09-2009

    How to post a comment and the page not reload?
    smo

    03-09-2009

    By using Ajax.
    Sumera

    11-11-2009

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

    19-11-2009

    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.
    Marcel

    26-12-2009

    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.
    Tunde

    29-12-2009

    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.
    niraj

    19-09-2010

    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.
    Khodor

    14-11-2010

    Is there any demo for this script
    Parkour

    05-01-2012

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

    23-04-2012

    Thankyou this script is quite nice and easy to work with
    mali

    30-06-2012

    Is there one without MY SQL
    malib

    10-12-2012

    is there 1 with sql???
    3R4

    11-02-2014

    I LOVE THIS SCRIPT
    Subhra

    18-07-2014

    Nice one
    Victor

    20-07-2014

    new post
    Jordan Rusnac

    27-12-2014

    heya this is the one im looking for
    Tania

    06-02-2015

    Is this using databse?
    tulasi

    27-03-2015

    thank for helpful script
    Tania

    15-06-2015

    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 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer