ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Internet & the Web

Php Tutorial: How to insert HTML comment section in any webpage or website using php?

Updated on November 3, 2011

This Tutorial (Php + HTML) will help you in learning 'How to insert a comment module or section on any web page', Requirements are shown below :

  • You should have an access to source code of your page,
  • Your web-host should support php (Your page must have extension of .php instead of .HTML or any other)
  • This scripts needs database.

Okay, Let we start our journey. You were always wondering about how to allow users to comment on your any web-page of your site, if you were new to programming field, So, I will try my best to solve this issue.

Just go to the database section that may provided to you by your host,

  1. Create a new database with your 'site name',
  2. Create a table with name 'comments' in the database you've created for your site,
  3. In the table named 'comments' create this attributes (Id, comment_on, comment_by, comment). Id should be set to 'int' and 'auto increment' while creating.

If you want to simplify your work and were unable to follow above steps,

  • Create a new webpage,
  • Save the below script (Little modifications should be done by your side) in that webpage or file,
  • Upload that file to your host via any ftp (file transfer protocol) protocol,
  • And, then open that file in browser and Your database and table will get created automatically.

<?php
/* U need to change below fields */
$db_sitename="Name of your site";
$db_hostname="Type the address of your database";
$db_username="Username used to access database";
$db_password="Password to access database";

/* Leave the script below as it is */
mysql_connect($db_hostname, $db_username, $db_password);
if(mysql_query("CREATE DATABASE $db_sitename"))
{
mysql_select_db($db_sitename);
mysql_query("CREATE TABLE comments
 (id INTEGER AUTO INCREMENT NOT NULL,
 comment_on VARCHAR(100) NOT NULL,
 comment_by VARCHAR(100) NOT NULL,
 comment TEXT NOT NULL)");
}
else
{
echo "error in script or check if database service has been provided to you by your webhost";
}
mysql_close();
?>
Source

Now, all the database issues have been resolved and we will see the HTML code and php script (To show previous comments) which you can place on any web page at it's end.

<form action="post_comment.php" method="post">
<table>
<tr><td>Comment On: </td><td><input type="text" name="comment_on" size=40 readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" /></td></tr>

<tr><td>Comment: </td><td><textarea name="comment" cols=30></textarea></td></tr>

<tr><td>Comment By: </td><td><input type="text" size=40 name="comment_by" /></td></tr>

<tr><td></td><td><input type="submit" value="Submit" /></td></tr>
</table>
</form>
<?php
/* U need to change below fields */
$db_sitename="sitename/database name in which u created tables";
$db_hostname="address of database (For Example: localhost)";
$db_username="username to access database";
$db_password="password of database";
$no_of_comments="Number Of comments u want to show on page";

/* Leave the script below as it is */
mysql_connect($db_hostname, $db_username, $db_password);
mysql_select_db($db_sitename);
$pagename=md5($_SERVER['PHP_SELF']);
$query=mysql_query("Select * from comments where comment_on='$pagename' ORDER BY id DESC LIMIT 0, $no_of_comments");
echo "<hr />";

echo "<h3>Latest Comments</h3>";
while($fetch=mysql_fetch_array($query)) {
echo "<p>".$fetch['comment']."<br/><sub><b>Comment by: </b>".$fetch['comment_by']."</sub><hr /><p>";
}
mysql_close();
?>

Create another web page with name "post_comment.php" and save the below script in that.

<?php
/* U need to change below fields */
$db_sitename="sitename/database name where u created tables";
$db_hostname="address of database (for example: localhost)";
$db_username="username used to access database";
$db_password="password to access database";

/* Leave the script below as it is */
mysql_connect($db_hostname, $db_username, $db_password);
mysql_select_db($db_sitename);
$comment_on=$_POST[comment_on];
$comment_by=$_POST[comment_by];
$comment=$_POST[comment];
$query=mysql_query("INSERT INTO 
comments (comment_by,comment_on,comment)
VALUES ('$comment_by','$comment_on','$comment')");
if($query) {
$ref=$_SERVER['HTTP_REFERER'];
echo "Comment Inserted";
header("location: $ref");
}
else {
echo "Error while inserting comment, Contact the <a href=\"http://shrikrishna.tk\">programmer</a> for any help.";
}
mysql_close();
?>

Hope, All the information provided here is easy to understand. Thanks for reading article.

Note: You can paste this code in your website template to make it run on your whole website - I know everybody knows that but listen you can use include("page address"); statement to include page containing the "HTML form + php code" i.e. middle two snippets of code shown in this article.

Beware of Spamming, You can use human verification for that.

Disclaimer: This Article has been created only for learning purposes.

Some programmers are facing problems while executing my Script (As seen from responses posted here). So, here is a little solution that I came up with.

if this part:

value="<?php print md5($_SERVER['PHP_SELF']); ?>"


is causing the problems, then you can replace it with this one:

value=<?php print "\"".md5($_SERVER['PHP_SELF'])."\""; ?>


And I hope, this will work. I tested this script 2-3 times before publishing and I think php runs in same way on all computers/laptops.
Thanks for notifying me about bugs in my script.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Rob 5 months ago

      Nice job

    • profile image

      Chad 3 years ago

      I know this was originally created years ago, but I just implemented it on my site, and it's working great. First of all, thanks for the great info. Now on to the question: how would I go about utilizing the "$no_of_comments" variable in conjunction with more comment pages? Is this something that would be easy to implement, or more trouble than it's worth? I don't anticipate having so many comments that just scrolling down would be an issue, but thought I'd ask anyway.

    • profile image

      me 3 years ago

      Make sure that you created a database having same table structure as specified in this article and also check if proper credentials of database were supplied for PHP variables before testing.

      The error specified by you will only occur when mysql query failed to execute properly.

    • itech profile image
      Author

      Krishna 5 years ago from New Delhi, India

      Make sure that you created a database having same table structure as specified in this article and also check if proper credentials of database were supplied for PHP variables before testing.

      The error specified by you will only occur when mysql query failed to execute properly.

    • profile image

      Qube 5 years ago

      When i click the submit button it always say "error while inserting comment.. can you help me with this itech!

    • profile image

      AndrĂ© 5 years ago

      I've checked my phpAdmin and I can see the comments I'm making all recorded there so don't see why they're not showing up?

    • profile image

      AndrĂ© 5 years ago

      Hey itech great tutorial really well written. Have got it to the point where it seems to be working but when I submit the comment, the page refreshs and no comments are shown under latest comments. Don't know why it's not showing up? Do you have any idea of what could be wrong?

    • profile image

      victor 5 years ago

      nice tutorials

    • itech profile image
      Author

      Krishna 5 years ago from New Delhi, India

      @Abdel Irada, You can send me a mail containing your code.... from my profile page.

    • profile image

      reuben 5 years ago

      very good

    • profile image

      Abdel Irada 5 years ago

      I'm brand-new to working with PHP, so I've probably made some elementary error, but I have implemented your code as I understand it.

      I no longer get error messages (since I added the lines "ob_start();", etc.), but comments appear as "0" and "Posted by: 0".

      Can you tell me what might be causing this? (I can post the code if necessary.)

    • profile image

      Abdel Irada 5 years ago

      I'm brand-new to working with PHP, so I've probably made some elementary error, but I have implemented your code as I understand it.

      I no longer get error messages (since I added the lines "ob_start();", etc.), but comments appear as "0" and "Posted by: 0".

      Can you tell me what might be causing this? (I can post the code if necessary.)

    • profile image

      sudhanshu saxena 5 years ago

      hi its really useful code

    • itech profile image
      Author

      Krishna 5 years ago from New Delhi, India

      You can insert as many comment sections on single page and the only thing you need to do is to replace "comment_on" field value with your own custom value.

      You can hide "Comment_On" form field by using hidden keyword inside input tag like as shown below.

      &lt;input type="hidden" name="comment_on" /&gt;

    • profile image

      nityata 5 years ago

      Hey :) really good post thanx a lot :) im having one error tho: the comment_by field is not getting stored in the database and hence not being displayed either. its displayed as comment_by: 0 . Do u have any suggestions. Also, as Mira asked can we hide the comment_on field. And last, what if there are many posts on a single page and each post requires a comment ? what should the comment_on take on as its value ? thanx :)

    • profile image

      Loon 5 years ago

      The PHP script is useful.But I need to make some adjustment for my website. Thanks!!!

    • profile image

      santosh 5 years ago

      hai im trying to make a comment page.

      but in this comment symbol(') will not get.

      and also comment comes only continous line.

      how to slow this

    • profile image

      moses 5 years ago

      coool

    • profile image

      Mira 5 years ago

      Hello, thank you so much for posting this article and making things so much easier for everyone! This is just what I wanted.

      I love your script, but it would be nice to hide the "Comment On" section. As I know this is crucial to the code, it obviously can't be deleted. Is there a way to hide it while still being able to send the necessary information? This would be very helpful!

      Again, thank you for all your help!

    • itech profile image
      Author

      Krishna 5 years ago from New Delhi, India

      @patric k, Here is the solution of your problem in official PHP website ... http://php.net/manual/en/function.header.php#refse... . If you will face difficulties, then, you are always welcome here.

    • profile image

      patric k 5 years ago

      Thanks alot itech for your quick reply. have done it and it works great. but there is this issue about headers being sent to the browser. nothing seems to solve it even the solution you have at the bottom of the site, i still get this:

      Comment Inserted

      Warning: Cannot modify header information - headers already sent by (output started at /home/merufocu/public_html/post_politicscomment.php:8) in /home/merufocu/public_html/post_politicscomment.php on line 27. please help

    • profile image

      Chris 5 years ago

      Thanks for your help :D

    • itech profile image
      Author

      Krishna 5 years ago from New Delhi, India

      @chri, which server software are you using... As per your knowledge and my experience, i would recommend "xampp" becoz it come prepackaged with all the necessary softwares such as apache, MySQL, mercury (used for emails), phpmyadmin, filezilla etc.

      Well, you can now proceed to next step.

    • profile image

      Chris 5 years ago

      Well since when I open the PHP script with chrome the page comes out black, I'll asume it created correctly.

      Where is it stored? or is it invisible? Can I proceed to the next steps?

    • itech profile image
      Author

      Krishna 5 years ago from New Delhi, India

      @chris, read the last section of this ( https://hubpages.com/technology/How-to-make-a-data... ) article which shows "How to Create Database manually using xampp and phpmyadmin".

    • itech profile image
      Author

      Krishna 5 years ago from New Delhi, India

      Yes, first snippet of php code in this article is doing that task... But only if MySQL is installed and running on your server. Are you getting blank page on running first snippet of code, It means your database has been created and you can use that (i.e. it's name) in other snippets of code.

    • profile image

      Chris 5 years ago

      Wait, how do I create a database? wasn't that script for creating it?

    • itech profile image
      Author

      Krishna 5 years ago from New Delhi, India

      did u created databse with same name which you are using as value of $db_sitename. I think you're not.

      You may have not specified path of files correctly in include(); or require(); functions/statements of php which is causing such type of error in dreamweaver. Sometimes, such errors have no meaning... So ignore them, if everything is ok.

    • profile image

      Chris 5 years ago

      Forgot to say, Dreamweaver reports this error (translated from spanish)

      "Can't resolve dinamically related files, the definition of the site is not correct for this server"

    • profile image

      Chris 5 years ago

      I tried again, here's my php file:

      $db_sitename="Proyecto Final de Introduccion a las TIC";

      $db_hostname="localhost";

      $db_username="root";

      $db_password="";

      Server settings:

      Name: Proyecto Final de Introduccion a las TIC

      Folder: C:\Users\Chris\Dropbox\Public\web\

      LocalServer. C:\Users\Chris\Dropbox\Public\web\ Local/net Test

    • itech profile image
      Author

      Krishna 5 years ago from New Delhi, India

      hello @patric,

      First Issue: See line number 18 (echo statement) of third snippet of code shown in this article. We are using '&lt;sub&gt;' html tag, which may be the reason for this issue OR it may caused by stylesheet (CSS) you linked to file containing this script.

      Second Issue: Below is the resolution of second issue.

      1) you need to create one more column in your database with name "datetime".

      2) In last snippet of code, define one more variable i.e. "$datetime=date("Y-m-d H:i:s");". In this date function, 'Y' represents Year, 'm' for month, d for 'day' and 'H' for hour, 'i' for minute, 's' for second. You can remove and add any of this characters from function as per your requirements and it will be stored in database like this "2011-11-08 14:43:25".

      3)In last snippet of Code, replace line 14-16 with this one, " $query=mysql_query("INSERT INTO

      comments (comment_by,comment_on,comment,datetime)

      VALUES ('$comment_by','$comment_on','$comment','$datetime')"); ".

      Hope, It is easier to understand.

    • itech profile image
      Author

      Krishna 5 years ago from New Delhi, India

      Hello @chris, You are doing one thing wrong here. If you are running this project on your local computer i.e. on "localhost" then, you should use "localhost" as value of "$db_hostname" and if you are running it on internet (online) then, you should use your domain i.e. something like "example.com".

      I think you're running it on local computer, Use "localhost" as value of $db_hostname, like this $db_hostname="localhost";

    • profile image

      Chris 5 years ago

      Hi, I'm trying to create a local webpage for a school project and I can't seem to get this right:

      First, I'm pasting the PHP code into a new PHP document in dreamweaver, I've set the following parameters:

      $db_sitename="Project";

      $db_hostname="files/";

      $db_username="root";

      $db_password="";

      Then I save the script and open it in Chrome, it shows a blank page with nothing on it, and nothing is generated in the files folder. What am I doing wrong?

      It might be worth nothing that my knowledge in HTML and PHP might be around 1%

    • profile image

      Patric 5 years ago

      I used the code above and it works great, but i have two issues i would love to ask:

      1. when i use it on a site i get very tiny fonts for the comments, what's the problem here

      2. what if i want to add the date and time the comment was posted?

      thanks in advance

    • itech profile image
      Author

      Krishna 6 years ago from New Delhi, India

      Ya, such type of Warnings may occur (in Some hosts)... you can avoid that by placing ob_start(); at starting and ob_end_flush(); at the end of php script on "post_comment.php" page.

      If warnings may still appear... then notify me....

    • profile image

      JJ 6 years ago

      ohhh...yes! I actually left that one out on purpose, because my SQL database would not accept it.

      My bad, I have inserted it now, and it works, however I get this error:

      Comment Inserted Warning: Cannot modify header information - headers already sent by (output started at /customers/mobilxx.dk/mobilxx.dk/httpd.www/skrivskriv/post_comment.php:18) in /customers/mobilxx.dk/mobilxx.dk/httpd.www/skrivskriv/post_comment.php on line 19

      line 18 and 19 is the following:

      echo "Comment Inserted";

      header("location: $ref");

      It works, but it keeps sending the error messager, which I would like to get rid of, any sugestions?

      Thank you for the help by the way, I think you have some greate things on your website.

    • itech profile image
      Author

      Krishna 6 years ago from New Delhi, India

      Ya, one column is missing in this syntax i.e.

      " comment TEXT NOT NULL "

      Your syntax is creating only two columns in database... i.e. comment_on and comment_by only....

      This new column will be used for storing actual comment (written by commentator) in your database.

    • profile image

      JJ 6 years ago

      Hi,

      I used the above script, or rather tried to.

      I have used in more or less in the original form, however I had to change the syntax of the database when creating it.

      I used the above instead:

      CREATE TABLE comments(

      id int(10) unsigned auto_increment,

      comment_on varchar(100),

      comment_by varchar(100),

      PRIMARY KEY (id)

      )

      Do you think that is a problem, because I keep getting an error when I try to insert a comment.

      You can tryk the URL, it will lead you to my comment test site. :)

      I get this error:

      Error while inserting comment, Contact the programmer for any help.

      I hope you can help!

    • itech profile image
      Author

      Krishna 6 years ago from New Delhi, India

      Good idea... You can do that easily by first storing "date and time" of comment in database.... Then, by calculating the time period between 'date and time of comment' and 'present date and time' programatically.

    • profile image

      Newbiesss 6 years ago

      thx itech. btw, i wish to add time and date beside each comment, or something similar to this page,[ itech 11 hours ago]... can u give me some ideas?

    • itech profile image
      Author

      Krishna 6 years ago from New Delhi, India

      "comment on" is refrencing to page address on which you were commenting....

    • profile image

      Newbiesss 6 years ago

      hi,

      im facing some problem here,

      i wonder what's is the"Commnet on :____" for?

      is it a display or user input?

      i did everyting based on the above tutorial, but why my result always display (error while inserting comment..)

      any idea?

      thanks.

    • profile image

      Newbiesss 6 years ago

      Comment On:

    • itech profile image
      Author

      Krishna 6 years ago from New Delhi, India

      you forgot to add "$" sign in variable name like this $db_username="richard2";

    • profile image

      Rick 6 years ago

      Hi

      I used this script but when I click submit button from the form I get the following error on the post_comment page

      Parse error: syntax error, unexpected T_STRING in /home/richard2/public_html/comments/post_comment.php on line 9

      currently on line 9 is:

      mysql_connect($db_hostname, $db_username, $db_password);

      I have changed these variable names to be appplicable to my site ie db_username="richard2" etc

      Any help would be greatly appreciated

    • itech profile image
      Author

      Krishna 6 years ago from New Delhi, India

      Thanks for notifying the problematic part in this script... I will change those database related variables.

      Thanks for commenting.

    • weekendrockstar profile image

      weekendrockstar 6 years ago from SE Pennsylvania

      @Shane: As long as your database credentials are between the PHP tags and do not follow an echo or print statement then they will not be viewable.

      @itech: Should you $salt the md5 encoding add an extra layer of 'protection' using it?

      Also, for the database credentials it may be helpful to append 'db_' to the variable names. It wouldn't make a difference to anyone that uses copy/paste to add it to their pages but for anyone that wants to add this to their own program $username and $password are too frequently used and could cause conflict.

      Otherwise I like what you did here.

    • itech profile image
      Author

      Krishna 6 years ago from New Delhi, India

      Hello Liz, You need to create two separate Pages... as shown Below,

      1) First For, Showing form and previous comments simultaneously on single page,

      2) Second for, Where our Form will be processed and this one should be named as "post_comment.php".

      Important Note: Keep both files in same folder/directory of webhost.

      You are free to create first page OR you can insert form code and php code followed next to it on any of your pre-built page.

      First snippet of php code in this tutorial/article may not work on most webhost becoz most of them don't allow programmers to create database through them via php script due to several reasons (you can create them manually using one of the tool provided in your control panel or via phpmyadmin on localhost).

      Hope, this helps.

    • profile image

      Liz 6 years ago

      Im still confused with your instructions. I'm new. how many pages we are suppose to create. I see you have 4 differents sets of information. 3 php's and 1 form. Are we supposed to create 4 scripts?

    • trimar7 profile image

      trimar7 6 years ago from New York

      Thank you for sharing your expertise with those of us who are still learning.

    • itech profile image
      Author

      Krishna 6 years ago from New Delhi, India

      @conan,

      Makes sure that your pages are having a .php extension instead of .html or any other (Whatever, you can also run php scripts on .html pages but after making changes in your .htaccess file.)

      see below (i.e. below comment posting area of this page), if that is your problem and needed solution.

      Hope, it helps.

    • profile image

      Conan 6 years ago

      ***I mean I cannot figure out what is the problem.***

    • profile image

      Conan 6 years ago

      Same problem as above poster, Jo Ann.

      I figure out what is the problem.

      But thanks for this helpful hub anyway!

    • profile image

      Jo Ann 6 years ago

      I tried this script and could not get it to work. when I put the php script at the bottom of my webpage, under the form code, the form 'value' has the actual php value in the comment txtbox. also the php code at the bottom of the web page, flows over the form itself.

      Its a great idea, wish I could get it to work. I hate blogs, they are way too chaotic for me.

      Thanx

    • tammyfrost profile image

      Tammy Frost 6 years ago from Oregon

      Great work on this hub. It is a popular request. Many website hosts don't support php. Thanks for sharing.

    • itech profile image
      Author

      Krishna 6 years ago from New Delhi, India

      Hey Mark, I tested this script on xampp also and it debugged successfully.

      It is not just the copy and paste script, You need to change values of variables in this code means you want to set values of $hostname, $username, $password etc.

      Default username for Mysql database is root and password is "" (means No Password), leave the password field blank.

      Before this go to http://localhost/phpmyadmin and create a new database with your site-name(recommended) and and then table and it's attribute as specified in top of this article.

    • profile image

      Mark 6 years ago

      There`s a fault in the script:

      SIZE=40

      You forgot the quotes; size="40".

      I can`t get this to work:

      Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'Mark'@'localhost' (using password: YES) in G:\SCHOOL\Programma`s\XAMPP\xampp\htdocs\home.php on line 34

      Warning: mysql_select_db() [function.mysql-select-db]: Access denied for user 'ODBC'@'localhost' (using password: NO) in G:\SCHOOL\Programma`s\XAMPP\xampp\htdocs\home.php on line 35

      Warning: mysql_select_db() [function.mysql-select-db]: A link to the server could not be established in G:\SCHOOL\Programma`s\XAMPP\xampp\htdocs\home.php on line 35

      Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) in G:\SCHOOL\Programma`s\XAMPP\xampp\htdocs\home.php on line 37

      Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in G:\SCHOOL\Programma`s\XAMPP\xampp\htdocs\home.php on line 37

      I copied the codes completely...

      I am a student and need to learn this.

    • profile image

      Mark 6 years ago

      There`s a fault in the script:

      Comment On:

    • profile image

      Rob 6 years ago

      I am looking for this script for a long time, Thanks comment system on a webpage is good for seo as it brings more taffic to your website.

    • profile image

      Santosh Hegde 6 years ago

      Very Interesting. i started to Modifying My site and want to adding a comments section to the web pages on my website. Thanks for posting this useful info

    • profile image

      Shane 6 years ago

      how is this secure? you say to paste the html and the php on the end of a php page?

      then it shows your mysql database information including password.

      i'm confused.

      i put the html and the php where i wanted the comments to show up and then made the separate php file.

      what was i supposed to do? it's not working...

    • itech profile image
      Author

      Krishna 6 years ago from New Delhi, India

      @dimitris

      Did u created the database (manually or with script provided here) with attributes specified above.

      Well, I've rewritten the scripts and fixed some bugs, Check Out this script.... Maybe Your issue would be resolved.

      Thanks for your visit.

    • profile image

      dimitris 6 years ago

      hi, i copy the code into my websites but when I click submit, the post_comment.php is just a blank page. What do I do wrong?

      Thanks for your efforts!

    • itech profile image
      Author

      Krishna 7 years ago from New Delhi, India

      @agvulpes, you can insert this comment section on any webpage (if you have access to source code of that page),

      Wordpress already have an built-in comment box.

    • agvulpes profile image

      Peter 7 years ago from Australia

      Nice hub and good info. I'm no expert but would it be easier to Install Wordpress to do this or is that an overkill just to get a comment box?

    • profile image

      ryan 7 years ago

      thanks for the post..

      is it not possible to insert a comment section in a html website ? I would like to have one on my personal website. if not i will have to think about learning php !!?? :-(

    • itech profile image
      Author

      Krishna 7 years ago from New Delhi, India

      0_o, I've never seen such a fast response ever, this article was just published few minutes ago,

      Thanks Shawn, You made my day and feeling great as you got the info of what you've looking for.

    • Shawn Scarborough profile image

      Shawn Scarborough 7 years ago from The Lone Star State

      Interesting Hub. I've been thinking about adding a comments section to the web pages on my website. Thanks for posting this info.