Simple MySQL Guestbook

Creating the guestbook has two parts, the table to hold the guestbook records and the script to insert and select records from the database
table.

The structure of the table should look similar to this:

CREATE TABLE guests (
id int(10) unsigned NOT NULL auto_increment,
guest varchar(50) NOT NULL default '',
message varchar(200) NOT NULL default '',
date datetime default NULL,
PRIMARY KEY (id)
) ;

The guestbook script has three sections - the code for the form, the code for saving the form data, and the code for displaying the data.

When the form is submitted, the data is sent to the the script itself, the message data is inserted into the database using an insert query.

To retrieve all records in the guests table use a select query then a while loop to print all the data.

PHP Code:

<?php
 
mysql_connect("localhost", "user", "password") OR die ("Connection Error to Server");
mysql_select_db("database") OR die("Connection Error to Database");
 
if ($action=="submit")
mysql_query("INSERT INTO guests SET message='$message', guest='$guest', date=NOW()");
 
// Now select all the data, and print it one by one.
 
$result=mysql_query("SELECT * FROM guests");
while($row=mysql_fetch_array($result))
print $row['guest']." : ".$row['message']." on ".$row['date']."<hr align=left width=100>";
?>
 
<form method="post" action="<?=$PHP_SELF?>">
Name:<br>
<input type="text" name="guest">
<br>
Message:<br>
<textarea name="message"></textarea>
<br>
<input type="submit" name="action" value="submit">
</form>

See it in action. ¦ Complete code.