PHP tutorial - comment form


Create comment form

You probably have seen a web page of a web site that allows you to post comments about your experience with te site or ask questions. In this tutorial, you will learn how to create a comment form to allow visitors to post comments and read the comments back to display in a web page. The all comments are saved in a database of MYSQL Server.

comment form in php

Now you need to create a database called commentdb and a table called tblcomments in MYSQL Server. You also have to create a user called test (with password test) to manage the database. You can use phpMyAdmin of WampServer to create the database, table, and user. The table has five fields: id, pname, comment, pdate, and url. The id is an auto increment field. It represents a unique identification number of a comment. The pname field stores the name of the visitor who posted the comment. The comment field is the description. The cdate field stores the date and time when the comment was created. The last field is url. It is the url of the web page on which the comment was posted.

comment table

After creating the database and table, you need to write php code to connect to MYSQL Server database, read comments from the tblcomments, and add new comments to the table. The DataHandler class in datamanip.php file below does these tasks for you. It will connect to the MYSQL Server database as the DataHandler object is created. The getComments function can be called to read all comments posted on a specific page from the table. The addComment is called to add a new comment to the table. The DataHandler class will be used on a web page that displays comments and allows visitors to post comments. In this tutorial, this page is called index.php.

<?php
class DataHandler{
private $con;
private $db;

public function DataHandler($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME){
$this->con=mysql_connect($DB_HOST,$DB_USER,$DB_PASS);
if (!$this->con) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
$this->db=mysql_select_db($DB_NAME,$this->con);
if (!$this->db) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
}

public function getComments($tblname,$curPage){

$query="SELECT * FROM ".$tblname." WHERE url='$curPage' ORDER BY pdate DESC";
$result=mysql_query($query);
$numrows=mysql_num_rows($result);
$str="";
if($numrows>0) {

$str="<table style='width:100%; border-spacing: 0 2px;' cellspacing='0'>";
while($datarow=mysql_fetch_row($result)){
$str.="<tr style='background-color:#f8f8f8'><td style='vertical-align: top; width: 78%'><img src='noname.png' width='50' height='50' style='float: left'/><p style='color:#ff9933;'>"."&nbsp;".$datarow[1]."</p><p style='padding-left:15px;word-wrap: break-word;'>".$datarow[2]."</p></td>"."<td style='text-align:right; width: 20%; vertical-align: top; border: 0px solid #f8f8f8'>".$datarow[3]."</td></tr>";
}

$str.="</table>";
}

else
$str.="<p><strong>No comments</strong></p>";
return $str;

}

public function addComment($na,$com,$cdate,$url){

//prevent injection
$name=mysqli_real_escape_string($na);
$comment=mysqli_real_escape_string($com);
$query = "INSERT INTO tblcomments(pname,comment,pdate,url) Values('$name','$comment','$cdate','$url')";
$result = mysql_query($query) or die ("Error:Couldn't execute query. Sorry for the inconvenience!\nPlease try again.");
echo "<p><h4 style='color:#0000FF'>Thank you! Your comment has been published.</h4></p>";


}

public function closeConnection(){
mysql_close($this->con);
}

}

?>

As the form to post comments might be placed on many web pages. So, it is a good idea to create a separate file for displaying the form. You will create a new file called commentform.php to display the form. There are four fields on the form: a text field to input visitor'name, a textarea for writing comment, a text field to input security code, and a submit button. Below is the content of the commentform.php file.

<form id="form1" name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<table width="100%" border="0" cellspacing="2" cellpadding="2" style="background-color:#efefef">
<tr>
<td width="500"><strong>Name</strong></td>
</tr>
<tr>
<td>

<label for="txtname"></label>
<input name="txtname" type="text" id="txtname" style="border:none; height:30px; width:300px" required>
</td>
</tr>
<tr>
<td><strong>Comment</strong></td>
</tr>
<tr>
<td>
<label for="txtcomment"></label>
<textarea name="txtcomment" id="txtcomment" cols="80" rows="10" style="border:none" required></textarea>
</td>
</tr>
<tr>
<td style="text-align:top">
<label for="txtcode"></label>
<input name="txtcode" type="text" id="txtcode" style="border:none; height:30px; width:300px;float:left" required>
<img src="captchaimg.php" width="100" height="30" alt="CAPTCHA"/>
<p>
<input type="submit" name="pub" id="pub" value="Submit" />

</p></td>
</tr>
</table>
</form>

The security code is displayed on a CAPTCHA image. It is a random six-character string. This image and security code is created in the captchaimg.php file. Here is the content of the captchaimg.php file.

<?php

//start session
session_start();
//generate random 32-character string
$md5_code=md5(rand(0,999));
//take only six characters from the code generated above
$s_code=substr($md5_code,15,6);
//store the security code in session
$_SESSION['security_code']=$s_code;
//define width and height of image
$mwidth=100;
$mheight=30;
//create blank image
$image=imagecreate($mwidth,$mheight);
//create colors
$black=imagecolorallocate($image,0,0,0);
$white=imagecolorallocate($image,255,255,255);
$grey = ImageColorAllocate($image, 210, 210, 210);
//set background color of the image to black
imagefill($image,0,0,$black);
//write security code on the image
imagestring($image, 3,30,3,$s_code, $white);
//draw shapes on the image
imagerectangle($image,0,0,$mwidth/2,$mheight/2,$grey);
imageline($image,0,0,$mwidth,$mheight/2,$grey);
//tell browse about the type of content to view
header("Content-type: image/png");
//create png image
imagepng($image);
//clean up resource
imagedestroy($image);

?>

Now, you will create the index.php page to display the comments and the form that allows visitors to post comments.

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Comment</title>
<style>

#pub{
background:#09C;
height:30px;
width:100px;
text-align:center;
padding-top:3px;
border-style:none;
color:#ffffff;
font:bold;
border-radius: 23px;
}
#pub:hover{
background:#666
}


</style>
<?php

//include datamanip file
include("datamanip.php");

//start session
session_start();

?>
</head>

<body>
<?php

//create DataHandler object
$dhandler=new DataHandler("localhost","test","test","commentdb");

//get the visited page url
$curPage=$_SERVER["REQUEST_URI"];
//read comments
echo $dhandler->getComments("tblcomments",$curPage);
//include comment form
include("commentform.php");
//the pub button is pushed to submit comment
if(isset($_REQUEST['pub'])){

     if($_REQUEST['txtcode']==$_SESSION['security_code']){
       $today=date("Y:m:d H:i"); //get the current date and time       
       $dhandler->addComment($_REQUEST['txtname'],$_REQUEST['txtcomment'],$today,$curPage);

     }
  else{
     echo "<p style='color:#ff0000'>Invalid code</p>";
     exit;

  }

}
$dhandler->closeConnection();
?>

</body>
</html>



Comments

ewewew comment

 ewewew

eeewew


2018-06-06
test comment

 test

test


2018-04-18
test233 comment

 test233

test


2017-11-13
test233 comment

 test233

test


2017-11-13
test comment

 test

test


2017-11-13
abv comment

 abv

hii


2017-09-09
test comment

 test

test


2017-06-16




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.