WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Forex Trading Online forex trading platform

Go Back Add a Comment Send this Article to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES SUBMIT AN ARTICLE PRINT
Title : Beginners guide to PHP and MySQL - Creating a simple guest book
Categories : Beginner Guides, To PHP, To MySQL, PHP, MySQL
Rafi Ton
Rafi Ton
Date : 2000-02-18
Grade : 5 of 5 (graded 3 times)
Viewed : 52286
Search : More Articles by Rafi Ton
Action : Grade This Article
Tools : My Favotite Articles


  Submit your own code examples 
 


In this tutorial we will build a simple php/mysql based guest book. Like my previous "Beginners Guide to PHP/MySQL" I will try to keep thinks as simple as possible. This tutorial mainly directed to people with small or none programming experience, nevertheless, I will assume that you have read my beginners guide to php/mysql.

Creating a new mysql database and table for the guest book:


Assuming that you have httpd/php/mysql running, the first thing we have to do is to create a new database and define a table, which will hold the visitors information inside:

As I explained before, in order to create a new database, we have to open the mysql terminal and enter:


mysql> create database guest_book; <enter>


Mysql should return something like:
Query OK, 1 row affected (0.06 sec)

Then, we have to choose the database we created by typing:


mysql> use guest_book; <enter>




Database changed

Now we can create the table for the information. I chose to create a table with timestamp, first name, last name, visitors email and the visitors comment.


mysql> create table visitors (TimeStamp varchar(20),
Name varchar(20), Last varchar (20), email varchar(40),
comment varchar(255));<enter>


MySQL should return something like:
Query OK, 0 rows affected (0.06 sec)

Displaying the information:



Next we will create a php script to display the information inserted in the table in a formatted table with some colors. The main and most important page is index.php3, which does the following things:
1. Displays the information in a table;
2. Displays 10 entries on each page, with NEXT and PREVIOUS options;
3. Allows to sort the entries by time, name, last and email.

Index.php3:


<html>
<head><title>Guest book - display the info&lt;/title>
&lt;/head>

<body bgcolor=#ffffff>

<?php

if (empty($srt)) {
$srt='TimeStamp';
}

if (empty(
$offset)) {
$offset='0';
}

echo
"<h2>Entries from the guest book sorted by $srt&lt;/h2>";


mysql_connect() or die ("Problem connecting to DataBase");
$query = "SELECT * FROM visitors order by $srt limit $offset,10";
$result = mysql_db_query("guest_book", $query);

if (
$result) { //Print results in table

echo "<table width=90% align=center border=1><tr>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?
srt=TimeStamp\">Visit time and date&lt;/a>&lt;/td>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?srt=Name\">User
Name&lt;/a>&lt;/td>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?srt=Last\">Last
Name&lt;/a>&lt;/td>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?
srt=email\">Email&lt;/a>&lt;/td>
&lt;/tr>"
;

while (
$r = mysql_fetch_array($result)) {
$ts = $r["TimeStamp"];
$name = $r["Name"];
$last = $r["Last"];
$email = $r["email"];
$comment = $r["comment"];
echo
"<tr>
<td>$ts&lt;/td>
<td>$name&lt;/td>
<td>$last&lt;/td>
<td>$email&lt;/td>&lt;/tr>
<tr> <td colspan=4 bgcolor=\"#ffffa0\">$comment&lt;/td>
&lt;/tr>"
;
}
//End while loop
echo "&lt;/table>";
}
//End if true
else { //Begin if false
echo "error.";
}
//end if false
mysql_free_result($result);

$next=$offset+'10'; //View next or previous entries
$prev=$offset-'10';

$query = "SELECT * FROM visitors";
$res = mysql_db_query("guest_book", $query);
$num=mysql_num_rows($res);

echo
"<table align=center><tr>";

if (
$prev>='0')
{
echo
"<form method=\"post\">";
echo
"<input type=hidden name=offset value=$prev>";
echo
"<input type=hidden name=srt value=$srt>";
echo
"<td align=center><input type=submit value='Previous Entries'>&lt;/td>";
echo
"&lt;/form>";
}

if (
$num>=$next)
{
echo
"<form method=\"post\">";
echo
"<input type=hidden name=offset value=$next>";
echo
"<input type=hidden name=srt value=$srt>";
echo
"<td align=center><input type=submit value='Next Entries'>&lt;/td>";
echo
"&lt;/form>";
}

echo
"&lt;/tr>&lt;/table>";

include (
'links.x');

?>


&lt;/body>
&lt;/html>


As you can see, I used the mysql_connect function with no information inside the (). If you use a remote computer of a unix based php/mysql you have to use a slightly different syntax: mysql_connect ('servername','your_username','your_password');

Well, this page is rather complex at first glance, but I will try my best explain it.

At the top of the page you can see the following section:


if (empty($srt)) {
$srt='TimeStamp';
}

if (empty($offset)) {
$offset='0';
}



Those two commands check whether I transferred data into the page or not, and if not it sets two default values that will be used later on. To check if I transferred any variables, I used the empty ($variable) command which returns false if $variable is set and has a non-empty or non-zero value; and returns true otherwise.

Once I set default values to my variables, I can query the MySQL database with:


$query = "SELECT * FROM visitors order by $srt limit $offset,10";
$result = mysql_db_query("guest_book", $query);


Notice that I used the two variables in this command (which at start hold the default values set previously). The order by $srt sorts selection by $srt (which holds TimeStamp as default) and limit $offset,10 gets the first 10 results starting with $offset.

The next section prints the results in a formatted table as I explained this in my Beginners Guide to PHP/MySQL. The only interesting thing is the sort options I added with:


echo "<table width=90% align=center border=1><tr>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?srt=TimeStamp\">Visit time and date&lt;/a>&lt;/td>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?srt=Name\">User Name&lt;/a>&lt;/td>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?srt=Last\">Last Name&lt;/a>&lt;/td>
<td align=center bgcolor=#00FFFF><a href=\"index.php3?
srt=email\">Email&lt;/a>&lt;/td>&lt;/tr>";


Here you can see how to transfer variables with links and not forms. I used the srt variable to transfer the sorting method to the page itself (or any other page for that matter).

Now I define two variables to be used later as new offsets for the next and previous entries on the table:


$next=$offset+'10';
$prev=$offset-'10';


Next I need to know the total number of entries on the table in order to see if I have more results or not:


$query = "SELECT * FROM visitors";
$res = mysql_db_query("guest_book", $query);
$num=mysql_num_rows($res);


I select all the rows from the table, and use the mysql_num_rows($res) which returns the number of rows in a result set.

Now consider the following php script:





if ($prev>='0')
{
echo "<form method=\"post\">";
echo "<input type=hidden name=offset value=$prev>";
echo "<input type=hidden name=srt value=$srt>";
echo "<td align=center><input type=submit value='Previous Entries'>&lt;/td>";
echo "&lt;/form>";
}

if ($num>=$next)
{
echo "<form method=\"post\">";
echo "<input type=hidden name=offset value=$next>";
echo "<input type=hidden name=srt value=$srt>";
echo "<td align=center><input type=submit value='Next Entries'>&lt;/td>";
echo "&lt;/form>";
}


Here I have two "if" conditions which check whether I have more entries in the table, whether I have previous entries or none. The script creates two small forms that transfer to the php script both the offset for the table and the sorting method.

At the end of the page I just add the links.x which holds any necessary additional links and voila.


Adding entries to the table:



Well, this one is easy. First I create a small form with the fields I want to use:


<html>
<head><title>Adding entry to guest book&lt;/title>
&lt;/head>

<body bgcolor=#ffffff>

<h1>Add an entry&lt;/h1>

<form method="post" action="add2tbl.php3">
<table width=90% align=center>
<tr><td>Name:&lt;/td><td><input type=text name='name' size=40
maxlength=100>&lt;/td>&lt;/tr>
<tr><td>Last Name:&lt;/td><td><input type=text name='last' size=40 maxlength=100>&lt;/td>&lt;/tr>
<tr><td>email:&lt;/td><td><input type=text name='email' size=40 maxlength=100>&lt;/td>&lt;/tr>
<tr><td>Your Comment:&lt;/td><td><textarea name=comment rows=4
cols=60>&lt;/textarea>&lt;/td>&lt;/tr>
<tr><td>&lt;/td><td><input type=submit>&lt;/td>&lt;/tr>
&lt;/table>
<input type=hidden name=timestamp <?php $dte=date("d/m/Y H:i:s");
echo
"value='$dte'";?>><br>
&lt;/form>
<?php include ('links.x');?>
&lt;/body>
&lt;/html>


The script itself is rather simple to anyone familiar with forms. The only interesting thing is the TimeStamp I used in hidden mode:


<input type=hidden name=timestamp <?php $dte=date("d/m/Y H:i:s");
echo
"value='$dte'";?>><br>
&lt;/form>


I just used the php date function to create a time stamp and use it as the fields default value. This enables me to make sure that if I want to delete or modify an entry I have a unique value to match.

All those values are transferred to another php script called add2tbl.php3 which inserts the data into the table:


<?
if ($name)
{
mysql_connect() or die ("Problem connecting to DataBase");
$query = "insert into visitors values
('$timestamp','$name','$last','$email','$comment')"
;
$result = mysql_db_query("guest_book", $query);
echo
'Thank you your input.<br><p>&lt;/p>';
}

include (
'links.x');
?>


Well, that's it for now.
Rafi Ton









Counting - Creating a GIF based counter using PHP and MySQL
Categories : Beginner Guides, PHP, To PHP, To MySQL, MySQL
Counting - Creating a more sophisticated GIF based counter using PHP and MySQL
Categories : Beginner Guides, MySQL, PHP, To PHP, To MySQL
Counting - Creating a simple counter
Categories : PHP, MySQL, Beginner Guides, To PHP, To MySQL
Jump Start to Easy URLs
Categories : PHP, Beginner Guides, MySQL, File System, To PHP
How TO Install PHP, Apache and MySQL on Linux or Unix
Categories : PHP, MySQL, Apache, Installation, Beginner Guides
Beginners guide to PHP and MySQL
Categories : PHP, Beginner Guides, Databases, MySQL, Installation
Who's Linking?
Categories : PHP, Beginner Guides, To PHP
Grabb'n and Pars'n
Categories : Beginner Guides, PHP, To PHP
Start Using MySQL
Categories : MySQL, Databases, To MySQL, Beginner Guides
How To add paging (Pagination) with PHP and MySQL
Categories : PHP, Beginner Guides, Databases, MySQL, HTML and PHP
Beginners Guide to PHP - Introduction to cookies
Categories : Beginner Guides, Cookies, To PHP, PHP
PHP 101 Part 9 of 15 : SQLite My Fire!
Categories : PHP, Beginner Guides, Databases, SQLite
Referer Statistics
Categories : PHP, MySQL, HTTP, Databases
Descriptions of Common Data Types
Categories : MySQL, Databases, PHP, PHP options/info, General
Creating an IE-Only Database Driven Menu System With PHP, MySQL and DHTML
Categories : PHP, MySQL, Databases, DHTML
Ilir Pruthi wrote : 8
Hi,

I really like your script but i`m having problems when showing the entries. It is not showing the entries. I`ll try to
debug it but just for your sake, please re-check your script to check if it works.

Bye
Roman Kostinski wrote : 20
Dear Rafi Ton,

I`d like to thank you for very very good guestbook
tutorial. It is a very useful script for MySQL & PHP3
beginers. It works fine, but there are problems if a
user add text contaning ` or / or "

Is there a method that allows put into guestbook
any symbols and then display them correctly?

I tried addslases & stripslashes but didn`t sucseed.

Thanks again.
Abhi wrote : 36
for me this scripts worked perfectly fine.
go and check it out at
http://www.icns.com/~abhishek/test/
thanks.
Geordie Robb wrote : 75
This worked fine for the simple database, I created the
db using a phpmyadmin interface, when I tried to create
a larger table with 33 fields the interface returned a
screen with only the field, length/set, and default
parameters. How do I specify a type in that case?
Anonymous wrote : 154
Thanks the script was quick easy and worked very well.
g.
Cory Callcott wrote : 217
If your having probs with your browers not displaying
the current information (displaying results from cache)
chuck this line of code at the top.

header ("Cache-Control: no-cache, must-revalidate");

this just tells the browser not to cache this page, load it
fresh each time.
Bill Reed wrote : 255
Question?
I have mysql active on my server, but I need to add
another database.

How do I open a connection to mysql? I read your
instructions and the commands you lisst for different
things, but my problem is wwhere do I need to be to
iniate the command? A frend craeted the database that
is active on the server now. But he was activated and
had to sship out, sso no longer available.

I am totally new to mysql.

I wish someone wwould write ssome instructions for
thse of usse that are completely new to mysql and want
to use it in our website.

Thanks,
Bill
Keith Drummond wrote : 258
Hi
Guest_book Looks great but why does it not work?
I get the following error messages
Failed opening `links x` for inclusion (include_path=")
Line 87.
Guest_Book entry failed opening `links x` for inclusion
(include_path=") Line 22

Any offers of help
ROn mckeever wrote : 287
The scripts worked fine once I created a file called
links.x. My question is what is that file used for???

Thanks
Anonymous wrote : 292
Im guessing links.x would be replaced with links.css ?

well it worked fine then ;p
Anonymous wrote : 295
10x for the tutorial, it was really useful, but i didn`t get
to configure the add.php link...... 10x anyway
Andy Rosenfeld wrote : 297
I must join the list of those who don`t understand what
links.x is, how to create it, or what it does. The guest
book works despite the error messages:
Failed opening `links x` for inclusion (include_path=")
Line 87.
Guest_Book entry failed opening `links x` for inclusion
(include_path=") Line 22

Are there answers listed to the questions previously
posted. If so, I wouldn`t be needing to add this one
(which is somewhat redundant).
Thanks
Anonymous wrote : 305
the kicker here:
in php4, the scope of the form variables is not consistent
with the add2tbl.php file. you have to insert the following
command in the add2tbl file in order for the http POST
variables to be in the correct scope:

import_request_variables ("p","");
Mike R. wrote : 316
Mines always says "Warning: Access denied for user"...
how do I fix that?
Mike R. wrote : 317
wait i go it
Mirza Cutuk wrote : 322
How can i use simple hyperlinks instead of those forms
to navigate the records. I can pretty easily incorporate
those forms into my page, but hyperlinks, as they show
as text would be lot easier to use.
Juris Zellis wrote : 326
A tourial for variable declaration in links would be very
helpful for beginers, I figured it out from this sample,
but it would be better if described separately.
<BR><BR>PS<BR>I have been wondering for a long
time what are thous wierd links for.
Roy Jorolan wrote : 328
This tutorial works fine for me.

Just remember to create a file "links.x and specify
the location of that file, on your script.
Steve Register wrote : 330
Thanks Richter Brandon!!!!!!!!!!! I`m new at PHP (but
not programming in general) And had been racking my brain
trying to figure out what was wrong. I had thought it was
some kind of difference in PHP3 to PHP4 but couldn`t figure
it out.

Thanks again
justin eve wrote : 375
the links x file is used to create the same links on the
bottom of each page. i made one for gonig back to the
begging of the guestbook and another for adding
entries to it, but where i learnt this from they had told
me not to put on for deleting or editing public posts jsut
rememeber the site add and add a link inside lets say
liek a admin page so no one else can get in and delete
or modify entries well have fun i have a working script
at my site now and i can try and help if you contact me
justin eve wrote : 376
oh and anywhere it said php3 i just changed top php to
make it easyer but u have to change that in side of the
files too or any of your links dont work
D W wrote : 380
Great tutorial. Simple to setup and worked well without too
many issues. Thanks