Creating a guestbook

In this tutorial I will show you how to create a simple guestbook where your visitors can leave messages which are stored in a MySQL database. It contains the basic functions and security settings.

After this short summary let’s see the steps how to realize it.

Step 1.
First of all try to think about what we need in this project. The most important is the main page where we can see the massages ordered by date. I personally like the newest on the top, but you can of course change it to the opposite order. So the main page contains the messages with the name of the writer and the datum when the message was submitted. The second most important functionality is to add new messages to the list. On the add page a visitor fill out a form with his/her name and the message and submit it. In this phase our script needs to do some input validations and security checks. As we want to store the messages in a database we need a connection to a MySQL server. As we need this connection in various files it makes sense to implement it in a separate file.

So at the end we need 3 files as follows:

  1.  index.php : This is the main page with the list of messages.
  2. add.php: This script adds new messages to the list.
  3. db.php: This script contains the database connection information and code. 
Let’s start with the implementation in opposite order.

Step 2.

Before implementing our database connection script we need to design our database structure.

We want to store in this tutorial the following data:

  • Visitor name
  • Message
  • Date and time when the message was added to the guestbook.
  • ID to uniquely identify a message.
As result the sql code to realize this looks like this:

             `id` int(11) NOT NULL auto_increment,  
             `name` varchar(100) default NULL,      
             `text` text,                           
             `insertdate` datetime default NULL,    
             PRIMARY KEY  (`id`)                    

Step 3.
So as we have the database table let’s try to connect to it. As this tutorial is not focusing on database issues so here I don’t make any long explanation. The db.php script just contains the important connection information than try to make a connection to the given MySQL server with the given user name and password. As next step it selects the right database. That’s all. All the other database queries will be implemented in the index.php and add.php scripts.

At the end our db.php script looks like this:

= "localhost";
$serveruser = "username";
$serverpwd  = "password";
$dbname     = "test";

$connection = mysql_connect($serverhost,$serveruser,$serverpwd);


[newpage=Page 2]

Step 4.
Without data in the database it makes no sense to implement the index page as it will not list any messages. So let’s follow the add.php script with we can add a new message to our guestbook.

Here we need an html form with a normal input field for the username and a text area for the message content. When the form is submitted the script will call itself as defined in the form action parameter.

The script checks at the beginning whether the form was submitted or not. If the submit button was pressed than the $_POST variable contains the “submitBtn” item and we can start with the form processing.

As first step we try to read out the name and the comment and set the actual date. In case of name and comment field we use the PHP built in function htmlentities() to avoid a cross side scripting security hole. This function converts all applicable characters to HTML entities so if a visitor try to insert a JavaScript code it will be converted to show the code itself and not to execute it.

Right after we will make a new check whether the name and comment is long enough. We don’t want to allow messages from user “A” with the only content “B”. Here you can change the values as you want.

If all validation was succeed than we compose the SQL query and execute it to insert a new record into the database.

As final step we will return to the main page.

The complete add.php code is the following:

    if (isset(
$_POST['submitBtn'])) {
$name     = (isset($_POST['name'])) ? addslashes(htmlentities($_POST['name'])) : '' ;
$comment  = (isset($_POST['comment'])) ? addslashes(htmlentities($_POST['comment'])) : '' ;
$actDate  = date("Y-m-d H:i:s");
//Minimum name and comment length.
if ((strlen($name) > 2) && (strlen($comment) > 5)){
$sql = "INSERT INTO guestbook (name,text,insertdate) VALUES (";
$sql .= "'".$name."','".$comment."','".$actDate."')";
header("Location: index.php");
    else {


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
  <h1>Add comment</h1>
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="gbook">
      <tr><th>Name:</th><td><input name="name" /></td></tr>
          <td><textarea name="comment" cols=30 rows=5></textarea></td>
      <tr><td colspan="2" align="center">
          <input type="submit" name="submitBtn" value="Add comment"/></td>
<?php } ?>   

Step 5:
As last step we implement the most important script which shows you all of the visitors comment available in your guestbook. Although this is the most important part it is not complicated at all. So let’s start with it. The theory is that we select all records from the database ordered by date descending and display them in an html table as separate rows. Besides this we need to put a link on this page to our add.php script allow visitors to add a new message to our guestbook. So, first we need to include our db.php script. Than compose the SQL query and execute it.


$sql = "SELECT * FROM guestbook ORDER BY insertdate DESC";
$result = mysql_query($sql);

Now create the relevant HTML content as well. After adding the link and heading information we will build a table. We make a loop which go through all selected records and display its content. Each record will be displayed in 2 rows. The first row contains the visitors name and date when the message was added and the second row contains the message itself.

That’s all.

The complete index.php looks like this:


$sql = "SELECT * FROM guestbook ORDER BY insertdate DESC";
$result = mysql_query($sql);

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
    <a href="add.php">Add a comment</a>
<?php while ($row = mysql_fetch_assoc($result)) { ?>
         <tr><th><?php echo $row['name']." - ".$row['insertdate']; ?></th></tr>
         <tr><td><?php echo nl2br($row['text']); ?></td></tr>
<?php } ?>