✪ Press “Next” to play the next song. ✪

Home Music Novels Blogs Politics News Contact



How to make a Comment System for your website



"This page has been created by an amateur with no programming background, for amateurs!"



Hey friends, I am sure there will be quite a few out there just like myself who don't come from a computing background but who are running some really simple personal websites. And I am sure they all want to have some sort of a commenting system running on their website so that they are able to get some sort of feedback from their visitors. And I am sure they all know how they can run a third party script to add a third party comment box to their website. But the thought that they will have to make an account with a third party website, and that their comments will exist on that third party's database is a big deterrent.

Well, don't worry folks, I am here to share with you what I've gathered after reading scores of threads and information about "php", the language used to script and create comment boxes. Without much further ado, here is the information that you need.

You basically need four things to run a comment box:

  1. Database: Which you have to create on your server. That is, log on to your website server and use MySQL software (Or the SQL software provided to you by your server) and create a database. Then use the phpAdmin software or any other php software provided by your server to create a table to store comments and other related data. If your served didn't provide these to you.. TOO BAD!! Commit suicide! Ok kidding! You will have to download the two softwares and install them onto your server.
  2. Form: Is the html form that you will provide at the end of your web pages for people to fill in their names and comments and then press submit to send the data.
  3. Php script to upload comments into database: This script will upload what people will submit using the form into the table in your database, for storage.
  4. Php script to download comments onto your webpage: This script will retrieve the comments posted on a page and display them on your webpage.

Now the way I've done it, I've added the form and php script for downloading comments into one file which is a better way as then all you need is run this file at the end of your webpages with a simple command and off you go.

Now before I explain the other details, let me share with you the syntax of the two files.

Form and php Script for comment retrieval

<html> <head> <title>form</title> </head> <body> <?php mysql_connect('localhost', 'webuser_dbuser', 'password') or die ('Error: ' .$mysql_error()); mysql_select_db('webuser_database'); ?> <div> <table> <tr><th>comment</th> <?php $sql = mysql_query("SELECT * FROM `webuser_database`.`table` WHERE topic = # LIMIT 0, 30 "); while($row = mysql_fetch_array($sql)){ $id = $row['id']; $topic = $row['topic']; $comment = $row['comment']; $name = $row['name']; $date = $row['date']; ?> <tr><th> <?php echo "$comment<br/>"; echo "<small>$name</small><br/>"; echo "<small>$date</small><br/><br/>"; ?> </th></tr> <?php }?> </table> </div> <div> <table> <tr><td> <form enctype="multipart/data-form" method="POST" action="post.php"> <input type="text" name="topic" value="#" disabled; hidden;/> <span>My name is:</span> <input type="text" name="name"/> <span>I would like to add:</span> <textarea name="comment" rows="9" cols="59"></textarea> <input type="submit"/> </form> </td></tr> </table> </div> </body> </html>

Php file for saving comments into your database table

<?php $id = $_POST['id']; $topic =$_POST['topic']; $name = $_POST['name']; if(!$_POST['name']) { die("You forgot your name.. And I don't know it either!"); } $comment = $_POST['comment']; if(!$_POST['comment']) { die("Are you sure you have nothing to say?"); } $date = $_POST['YYYY-MM-DD HH:MM:SS']; mysql_connect('localhost', 'webuser_dbuser', 'password') or die ('Error: ' .$mysql_error()); mysql_select_db('webuser_database') or die('Error: '.$mysql_error()); $sql= "INSERT INTO `webuser_database`.`table` (id, topic, name, comment, date) VALUES (NULL, '$topic', '$name', '$comment', CURRENT_TIMESTAMP)"; mysql_real_escape_string($id); mysql_real_escape_string($topic); mysql_real_escape_string($name); mysql_real_escape_string($comment); stripslashes(nl2br($id)); stripslashes(nl2br($topic)); stripslashes(nl2br($name)); stripslashes(nl2br($comment)); $query= mysql_query($sql) or die("Error: ".mysql_query()); if(!$query){ echo "Uh oh!! Now you will have to write all that again!!<br/>"; echo "<a href='https://www. websitename. com'> Click here for a free return ticket!!</a>"; } else{ echo "Yeah you did it!! Let's party now!!Abducting you to my virtual home now!"; echo ("<meta https-equiv='Refresh' content='3; url=https://www. websitename. com'>"); } mysql_close(); ?>

The fine details of the project

Before we go any further, here are a few things that I would like to share with you about php:

  1. When writing in php make sure that you close all the quotes and brackets you use with their opposite number otherwise your php script will generate error and you will get nowhere. So for every ', ", <, (, { and [, make sure you put its' opposite number ', ", >, ) } and ].
  2. In php a double quote mark " means the end of script unless it is followed by either a dot . or a semi colon to continue it further ; which basically means if you forget one of these in the middle, your script will end at the double quote mark and will generate an error.
  3. Whenever you put a semi colon ; make sure you leave the next line empty. I read it at one of the sources that sometimes the php skips reading the next line after semi colon. I cannot confirm it for you but it's better to be safe than creating a baby.
  4. Although ?> sign means the end of script but if you will not close your database with a mysql close () command at the end of the file, your database will not close putting extra load on your server. Once again I cannot confirm it but it doesn't hurt anyways. Just a few words.
  5. It is always a good idea to add a die("Error..") statements so that if something is wrong with the script you don't have to smash your head into the side wall, monitor or your desk, nor you need a hammer to operate your system.

Rest of the points I will explain as I will give the details of the two files.

Let us first talk about database and table:

You will need to use mysql database software provided by your server (99.99%) or downloaded and installed by you on your server, to create a database which will hold your records for you. The name of the database generally is the name you give but in case you are using MySQL the name will be 'username_database' where username refers to the username you use to log into your server to manage your website and database is the name of the database you created. But don't worry, your MySQL software will show the name of the database and the name of the user of the database to you anyway.

Next you will need to create a user for the database using the same software and give it all the authorities over the database you created. (In php file I will mention two strings which are highly important to protect your database details but in a moment). The name of the user in case you are using MySQL will once again be 'username_dbuser' with the parts of the name once again being your server username and the username for the database that you chose.

With all this done, next thing you will need to do is create a table using the phpMyAdmin software, once again either provided by default by your server (web-host) or installed by you on the server. I would like to mention here that the names of the fields that you use for your table, your website visitors will never know them so you preferably keep them simple like I have used (id, topic, comment, name and date - all in small letters to cut the crap out). As you can see I am no programming guru, so the simple things work for me and simple things is what I recommend.

Now while creating your table make sure you don't tick the NULL box so that it's value remains NOT NULL. The five fields that I have used are the basic requirements for a very simple comment system, simple in technique but not in looks as you can notice in the comment box below. For id and topic select the value INT as input type (Which I guess means integer or number) while VARCHAR for comment and name as they can include any type of character (sexy, bitchy, noble - Nah! I mean text, number or special character). While date should be set on "Timesstamp" which means your server will auto update the date column for you every time a new comment will be added to your database. For value (Or I think Maximum value) tick the A_I (which means Auto Increment) box for id as that will enable your server to auto enumerate the comments your page receives like 1, 2, 3, 4 etc. In other words, one headache less. For topic you can select the maximum value to 100 (which is a lot of characters) and I will explain this when I will explain the form. For name, again 100 characters is more than enough unless you expect an entire family to put their names and surnames in one box when they comment. I don't! So I've left it to a more genuine 100 figure. Comment can be as long as you want it to be. For me 1000 was enough. At the end of all this your table should look like this configuration:

id INT Auto_Increment NOT NULL topic INT 100 NOT NULL name VARCHAR 100 NOT NULL comment VARCHAR 1000 NOT NULL date CURRENT_TIME NOT NULL

Now we are ready to create and use the form cum comment download file and link the form with the comment saving file (which I call post.php but you can call it honulu.php or scoobydoo.php whatever you like).

Form cum Comment download file:

Now before I explain this file I wish to draw your attention to two very important things. Firstly, these two files are php files with a .php extention. And php files donot work with html websites as such unless you tweak your website setup (which luckily is easier than picking your nose) and then add a small string at the end of your webpage html (which is irritating like girlfriends but is as pleasurable).

First, to tweak your website, if you have apache handlers provided to you by your server you are in for some luck otherwise happy Googling!! Anyway, I guess you have apache handlers software, or you will have to manually add the command lines ".htm server parsed" and ".html server parsed" to your ".htaccess" file on your server. That is, go to file manager, search .htaccess file and edit it. This means that your sever will treat php files as html files. Piece of cake!! Or is it?

But if you are lucky (If you are you should be buying $20 Million Super Lotto ticket!! What are you doing creating a website?) you will have apache handler on your server and you can use that to add handler "server-parsed" to .html and .htm extensions SEPERATELY (Yeah you will have to type the same thing over again twice, unless you prefer copy paste).

Once this has been done, the next step is to create the form.php and post.php files and then add the following string (please remove the spaces between the arrow-heads and string at either end before using it; also, you will have to replace the file name with whatever you call your file) at the end of your html webpage (before you close the body and html though, perhaps in a seperate table like I have, to give it a nyesh/nice background). The string is:

< !--#include virtual="/form.php"-- >

And this string is based on the assumption that you have kept your form.php file in the main folder of your website, which I know you won't if you will follow what I am saying as I will explain why in a moment. Else the file name will be "/folder/folder/form.php" depending upon how many subfolders deep your website runs from your main folder.

The second file: 'form.php'

The first thing you will notice is that the file has been made to look like a html file but it is actually written using notepad and is saved as .php. If your notepad saves it as form.php.txt then rename it. If it gives you warning that the file may become unusable, ignore it. After all who's the boss, you or your computer? Who knows better until the system is running? Kidding but you'll still have to do what I said.

This file actually includes both the comment retrieval system and the form. You can actually create only a comment retrieval file and add the form to the main html document but then you will end up copy pasting it every time you will create a webpage. Whichever way you prefer it doesn't make any difference.

Now for the php part the first thing you need to do is create a command that will open your database located on your server which makes up the first two queries in the file after the ends the first part of the script. The names used here have obvious meanings but I will still explain.

  1. localhost: The name of your server. You can find this on the top left corner of your phpAdmin.
  2. webuser_dbuser: The name of the database user that you created in MySQL.
  3. password: The password you set for the database user.
  4. webuser_database: The name of the database you created in MySQL.

Then we have the description of a table which we will use to display the comments. I used FrontPage to create the look of the table according to the background and look of the website that I wanted. There is no reason why you cannot do that unless of course it's your girl who decides it for you. Grrr..

Anyway, in the next query you ask your database to send comments according to the topic number (He!! He!! He!! I told you I will explain this later).

Now, if you read blogs or other websites which have comments enabled, you will notice two things about them. Firstly they are mostly php websites (and I've read somewhere that html websites are better and more efficient although I don't know what fields we ask the html websites to plough for us that php websites won't. But then I am no expert) and the second thing you will notice about them is, their pages are generally identified by numbers rather than names. Now this may not be a hard and fast rule but it is a general observation.

The reason is, these websites allot every webpage a number which identifies them for their associated database entries. So their form submits data according to their name numbers and the same data is retrieved by the comment retrieval file according to the same number. That number is echoed from either their page titles or a separate heading included in their html which echoes that number. This system adds two commands to your page; one is ( put above everything else on the page including doctype, and the other () right next to the place where that number has been inserted in the page. But I wasn't sure about how to do it, so I designed my own method.

Now I have the common file that saves comments to the database that I call post.php, in the main folder of my website, while I copy paste and rename my form file according to the name of the page that I am creating and put it in a seperate folder which houses my comment form pages in subfolders according to the sections of my website.

Now you will notice in the command $sql I have mentioned the topic = # which identifies to the database which page's comments are needed for displaying.

This number is provided with the comment and name by the form that I have typed after the query.

I may mention over here, to know the best way of knowing what syntax of the query will work with your server, go to the phpAdmin, open your database, then open your table, then click on search, then check for an entry which you inserted in the table yourself, by using any topic id. The data you entered will be displayed. But that does the trick for us. Use the "Show as php statement" (A small line in the corner of the message) to make your phpAdmin generate the syntax for you. Copy that syntax, click on the query button and test it in your phpAdmin itself. Most likely you will have to remove \' \' symbols. But you will get a working query which is the most important part, else your script will not work but only generate error after error.

The $row = mysql_fetch_array command fetches the comments, names, dates and ids for the topic #.

Then I have added the details of the table row where all these will be posted followed by the echo commands which determine the format in which they will be posted.

Last part of this file is the form.

When you begin form it is really important to mention the method and action of the form along with the encryption type so that the server knows the data consists of many parts and will be posted through a connecting file mentioned as the file the form acts on, post.php in my case. Remember to close the form after you have put all the inputs including submit button (And if you want to, even a reset button. Don't you wish we had the same liberties with our girlfriends. If you don't like 'em, reset their brains).

You would have noticed how the names of the input fields correspond with the names I have picked up for my table headings. These are the fields that post.php file will use to associate your data with your database. You would have also noticed how the input for topic in the form has been disabled and hidden. It is disabled so that your users cannot alter what you have put in as their value by default, else the comments about weather might end up on the page for romance, or whatever you have on your website. You get the zest of it. It is hidden because I don't want my visitors to see a nagging input box they can do nothing with. It irritates them as it reminds them of their partners.

Anyway, next up is the last part, the post.php file.

Php file to save comments into the database:

In this file the first thing you will notice is how we have mentioned what to get from the form to post in database. Both id and date are auto updated by our server so they are not input by us or the users but have been mentioned here as with every comment, they need to be added to the database as well, even if automatically by our server.

The next thing you notice will be the two "if" queries associated with the two fields that users will input in our form. These queries are there to make sure users submit only a filled form. If they fail to fill either or both fields, their comment will not be submitted and instead they will get the message we have included with "echo" command. You can say anything you want to in the echo command, use healthy swear words if you like to and don't want many visitors, for example "Yippeekaye Thumb Sucker!! Who will fill up the form? Your daddy?"

Anyway, next comes the opening of connection with the database, again two commands similar to the one's in form.php.

Then comes the query and now you know how to generate it's code. Only this time we will use insert in place of search and we will insert a blank query.

Once the syntax is generated, before you input any data into your database by running the query, you need to check your data is clean (As you will notice in my post.php file). Two queries should be run for each field that is going to be entered into the database:

mysql_real_escape_string($); stripslashes(nl2br($);

This is done to avoid what is referred to as "SQL injection"!

An "SQL injection" refers to some intelligent dude who is a million times better in programming then me, inputting a php string in your data fields instead of the data expected. That string will compromise your database's entire data to him. So if you are using your database to store passwords of your users, well "TaTa"!

After you have taken the necessary precautions, then run the query and you will be one happy chappy and your visitors, delirious.

Once again, the content of echo commands is in your hands but what after the comment has been submitted or rejected? Where do your visitors go from there?

You can direct them back to the page they came from or some other page or website, and there are three ways to do it.

  1. Using Javascript which I don't know, so can't tell.
  2. Using Headers (But they need to be used after sign, not even an empty space, leave alone a line, or you will get an error, headers already sent.) The best part of this is, since I don't know how to use them, I haven't used them and I cannot explain them. Best of luck googling.
  3. The third method and the one that I have used is the meta-tag syntax which auto redirects the visitors to my homepage after the time that I have set as content=3 i.e. 3 seconds (Note however, the single quote I've used ahead of 3 is closed after the web address). I want them to read what I have written in echo statement as you can see I am very funny. Anyway you can direct them to any page but I didn't want to create many php files to do it, so I took the best approach available to me within my limitations, send 'em all to my homepage.

There is one more approach. You can echo a statement and then add the text "Click here to go to.." (Wherever you want them to go) and then add "" which will convert your golden words into a default blues/violet hyperlink depending upon the colour code you have selected for your webpages. The same thing as meta-tag, I guess. I used meta-tag to impress girls.

Anyway, that's a lot of the boring geeky stuff. See you some other time. If any doubt or question, "Don't ask me! GOOGLE!"

Kidding! We'll google together, you at your place, me at mine!

Take Care,
Fatal Urge Carefree Kiss (Amanpreet Singh Rai)







Home Music Novels Blogs Politics News Contact