In this tutorial, we will be creating a basic 'Shoutbox' system with PHP. Aimed at beginners to PHP development, this allows you to get your feet wet working with databases before moving on to some of the more advanced PHP tutorials here at NETTUTS.
Introduction
This tutorial will guide you through the process of creating a basic "shoutbox" with PHP, using a MySQL database to store the shouts - and then make it look nice with some CSS. The tutorial is aimed at designers who are confident with HTML & CSS, but want to try their hand at developing with PHP.
Following the tutorial, you should hopefully have a good understanding of the basics of using PHP to communicate with a database to send, request and receive information. We will also be including the use of Gravatars in our Shoutbox, adding that little extra oomph!
For those who haven't, I recommend you read our PHP From Scratch series in order to understand exactly what PHP is, and get a look at some of the basic syntax and how we use variables.
The sources files are also commented for those who would prefer to learn that way.
Step 1 - Getting Started
Database
Before starting, you should already have a database setup on your web server. Make sure you have the following details at hand:
- Hostname (eg. localhost)
- Database name
- Username for database
- Password
In the database, you will need to create a table named shouts with five fields:
- id
- name
- post
- ipaddress
To create this, run the following SQL code. You will normally run this from the SQL tab in phpMyAdmin.
1 |
|
2 |
CREATE TABLE `shouts` ( |
3 |
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, |
4 |
`name` VARCHAR(45) NOT NULL, |
5 |
`email` VARCHAR(60) NOT NULL, |
6 |
`post` TEXT NOT NULL, |
7 |
`ipaddress` VARCHAR(45) NOT NULL, |
8 |
PRIMARY KEY (`id`) |
9 |
);
|



You should receive a "Your SQL query has been executed successfully" message
The Files
We will need three files created for this project:
- index.php
- style.css
- db.php
You will also need a folder with our required images. Grab this from the source files.
Database Connection Details
The db.php file will be used to store our database details. Open it and insert the following code:
1 |
|
2 |
<?php
|
3 |
$host = 'localhost'; //usually localhost |
4 |
$username = 'root'; //your username assigned to your database |
5 |
$password = 'password'; //your password assigned to your user & database |
6 |
$database = 'shoutbox'; //your database name |
7 |
?>
|
Step 2 - Interaction
Start your index.php file with the following code, it just begins our document and places a few sections to style later.
1 |
|
2 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
3 |
<html xmlns="http://www.w3.org/1999/xhtml"> |
4 |
<head>
|
5 |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> |
6 |
<title>Shoutbox for NETTUTS by Dan Harper</title> |
7 |
<link rel="stylesheet" href="style.css" type="text/css" /> |
8 |
</head>
|
9 |
<body>
|
10 |
<div id="container"> |
11 |
|
12 |
<h1>Shoutbox</h1> |
13 |
<h5><a href="http://www.danharper.me" title="Dan Harper">Dan Harper </a> : <a href="http://www.nettuts.com" title="NETTUTS - Spoonfed Coding Skills">NETTUTS</a></h5> |
14 |
|
15 |
<div id="boxtop" /> |
16 |
<div id="content"> |
Establishing a Connection
Before we can do anything with a database, we need to connect to it. Insert the following after the previous code. It is explained below.
1 |
|
2 |
<?php
|
3 |
$self = $_SERVER['PHP_SELF']; //the $self variable equals this file |
4 |
$ipaddress = ("$_SERVER[REMOTE_ADDR]"); //the $ipaddress var equals users IP |
5 |
include ('db.php'); // for db details |
6 |
|
7 |
$connect = mysql_connect($host,$username,$password) or die('<p class="error">Unable to connect to the database server at this time.</p>'); |
8 |
|
9 |
mysql_select_db($database,$connect) or die('<p class="error">Unable to connect to the database at this time.</p>'); |
The first two lines use a built-in PHP function to get the name of this file, and the other line to get the visitors IP address. We will use the two variables later in the tutorial.
We then include our db.php file so we can retrieve the database details you filled in. Alternatively, you could paste everything from db.php here, but it's good practice to separate the details.
$connect stores a function to use our database details in order to establish a connection with the database server. If it can't connect, it will display an error message and stop the rest of the page loading with die().
Finally, we connect to our database.
Has anything been submitted?
The next thing we will do is check whether someone has submitted a shout using the form (which we will include shortly). We check the documents POST to see if something has been submitted from a form.
1 |
|
2 |
if(isset($_POST['send'])) { |
3 |
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['post'])) { |
4 |
echo('<p class="error">You did not fill in a required field.</p>'); |
5 |
} else { |
We start with our if() which checks our POST to see if an item named 'send' has been submitted. If it has we use the empty() function to make sure the 'name', 'email' and 'post' fields were filled in. If they weren't, we display an error.
Otherwise, we continue:
1 |
|
2 |
$name = htmlspecialchars(mysql_real_escape_string($_POST['name'])); |
3 |
$email = htmlspecialchars(mysql_real_escape_string($_POST['email'])); |
4 |
$post = htmlspecialchars(mysql_real_escape_string($_POST['post'])); |
5 |
|
6 |
$sql = "INSERT INTO shouts SET name='$name', email='$email', post='$post', ipaddress='$ipaddress';"; |
7 |
|
8 |
if (@mysql_query($sql)) { |
9 |
echo('<p class="success">Thanks for shouting!</p>'); |
10 |
} else { |
11 |
echo('<p class="error">There was an unexpected error when submitting your shout.</p>'); |
12 |
}
|
13 |
}
|
14 |
}
|
On the first three lines, we run each of our fields (name, email and post) through the htmlspecialchars() and mysql_real_escape_string() functions and place them into their own variables.
htmlspecialchars() is a function designed to prevent users from submitting HTML code. If we didn't do this, someone could put any HTML into our database which would then be executed to other users. This is especially bad if someone submitted javascript code that would transfer visitors to a malicious website!
mysql_real_escape_string() is a similar function. Except this one stops the user from submitting any sort of SQL code to the server. If we didn't do this, someone could execute code to steal, edit or erase our database!
Using our new details, we create a SQL query to insert the submitted shout into the database. In the if() tags, we execute the SQL Query. If the query was successfully executed, and the shout added to the database, we display a "Thanks for shouting!" message; otherwise we display an error.
Retrieving the Shouts
We will now retrieve the 8 latest shouts from our database to display them to the user.
1 |
|
2 |
$query = "SELECT * FROM `shouts` ORDER BY `id` DESC LIMIT 8;"; |
3 |
|
4 |
$result = @mysql_query("$query") or die('<p class="error">There was an unexpected error grabbing shouts from the database.</p>'); |
5 |
|
6 |
?><ul><? |
On the first line, we create a new SQL query to "Retrieve all fields from the 'shouts' table, order them descending by the 'ID'; but only give us the latest 8".
On the second line we execute the query and store it in $result. We now:
1 |
|
2 |
while ($row = mysql_fetch_array($result)) { |
3 |
|
4 |
$ename = stripslashes($row['name']); |
5 |
$eemail = stripslashes($row['email']); |
6 |
$epost = stripslashes($row['post']); |
7 |
|
8 |
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70"; |
9 |
|
10 |
echo('<li><div class="meta"><img src="'.$grav_url.'" alt="Gravatar" /> |
11 |
<p>'.$ename.'</p></div><div class="shout"><p>'.$epost.'</p></div></li>'); |
12 |
|
13 |
}
|
14 |
?></ul> |
The first line says "While there are still rows (results) inside $result, display them as follows:".
stripslashes() removes any slashes which mysql_real_escape_string() may have inserted into submissions.
$grav_url creates our Gravatar from each users email address.
We then output (echo) each shout in a specific manner. Basically displaying the Gravatar, Name and Shout in a list we can easily style later.
The Form
The final step for this page is to include a form to the bottom of the page which users can submit posts through.
1 |
|
2 |
<form action="<?php $self ?>" method="post"> |
3 |
<h2>Shout! </h2> |
4 |
<div class="fname"><label for="name"><p>Name:</p></label><input name="name" type="text" cols="20" /></div> |
5 |
<div class="femail"><label for="email"><p>Email:</p></label><input name="email" type="text" cols="20" /></div> |
6 |
<textarea name="post" rows="5" cols="40"></textarea> |
7 |
<input name="send" type="hidden" /> |
8 |
<p><input type="submit" value="send" /></p> |
9 |
</form>
|
10 |
|
11 |
</div><!--/content--> |
12 |
<div id="boxbot"></div> |
13 |
</div><!--/container--> |
14 |
</body>
|
15 |
</html>
|
Note that we reference the $self variable to tell the form where to send it's results; and we also send via the POST method. Below the form we close off any HTML tags we opened.
Styling
Try it out! You've finished all the PHP code, and you should be able to add a new shout and see the 8 latest ones.



However, there's one problem. It looks UGLY! Lets sort that out with some CSS :) With this not being a CSS tutorial, I won't go over any of the styling, but everything's pretty basic.
1 |
|
2 |
* { |
3 |
margin: 0; |
4 |
padding: 0; |
5 |
}
|
6 |
|
7 |
body { |
8 |
background: #323f66 top center url("images/back.png") no-repeat; |
9 |
color: #ffffff; |
10 |
font-family: Helvetica, Arial, Verdana, sans-serif; |
11 |
}
|
12 |
|
13 |
h1 { |
14 |
font-size: 3.5em; |
15 |
letter-spacing: -1px; |
16 |
background: url("images/shoutbox.png") no-repeat; |
17 |
width: 303px; |
18 |
margin: 0 auto; |
19 |
text-indent: -9999em; |
20 |
color: #33ccff; |
21 |
}
|
22 |
|
23 |
h2 { |
24 |
font-size: 2em; |
25 |
letter-spacing: -1px; |
26 |
background: url("images/shout.png") no-repeat; |
27 |
width: 119px; |
28 |
text-indent: -9999em; |
29 |
color: #33ccff; |
30 |
clear: both; |
31 |
margin: 15px 0; |
32 |
}
|
33 |
|
34 |
h5 a:link, h5 a:visited { |
35 |
color: #ffffff; |
36 |
text-decoration: none; |
37 |
}
|
38 |
|
39 |
h5 a:hover, h5 a:active, h5 a:focus { |
40 |
border-bottom: 1px solid #fff; |
41 |
}
|
42 |
|
43 |
p { |
44 |
font-size: 0.9em; |
45 |
line-height: 1.3em; |
46 |
font-family: Lucida Sans Unicode, Helvetica, Arial, Verdana, sans-serif; |
47 |
}
|
48 |
|
49 |
p.error { |
50 |
background-color: #603131; |
51 |
border: 1px solid #5c2d2d; |
52 |
width: 260px; |
53 |
padding: 10px; |
54 |
margin-bottom: 15px; |
55 |
}
|
56 |
|
57 |
p.success { |
58 |
background-color: #313d60; |
59 |
border: 1px solid #2d395c; |
60 |
width: 260px; |
61 |
padding: 10px; |
62 |
margin-bottom: 15px; |
63 |
}
|
64 |
|
65 |
#container { |
66 |
width: 664px; |
67 |
margin: 20px auto; |
68 |
text-align: center; |
69 |
}
|
70 |
|
71 |
#boxtop { |
72 |
margin: 30px auto 0px; |
73 |
background: url("images/top.png") no-repeat; |
74 |
width: 663px; |
75 |
height: 23px; |
76 |
}
|
77 |
|
78 |
|
79 |
#boxbot { |
80 |
margin: 0px auto 30px; |
81 |
background: url("images/bot.png") no-repeat; |
82 |
width: 664px; |
83 |
height: 25px; |
84 |
}
|
85 |
|
86 |
#content { |
87 |
margin: 0 auto; |
88 |
width: 664px; |
89 |
text-align: left; |
90 |
background: url("images/bg.png") repeat-y; |
91 |
padding: 15px 35px; |
92 |
}
|
93 |
|
94 |
#content ul { |
95 |
margin-left: 0; |
96 |
margin-bottom: 15px; |
97 |
}
|
98 |
|
99 |
#content ul li { |
100 |
list-style: none; |
101 |
clear: both; |
102 |
padding-top: 30px; |
103 |
}
|
104 |
|
105 |
#content ul li:first-child { |
106 |
padding-top:0; |
107 |
}
|
108 |
|
109 |
.meta { |
110 |
width: 85px; |
111 |
text-align: left; |
112 |
float: left; |
113 |
min-height: 110px; |
114 |
font-weight: bold; |
115 |
}
|
116 |
|
117 |
.meta img { |
118 |
padding: 5px; |
119 |
background-color: #313d60; |
120 |
}
|
121 |
|
122 |
.meta p { |
123 |
font-size: 0.8em; |
124 |
}
|
125 |
|
126 |
.shout { |
127 |
width: 500px; |
128 |
float: left; |
129 |
margin-left: 15px; |
130 |
min-height: 110px; |
131 |
padding-top: 5px; |
132 |
}
|
133 |
|
134 |
form { |
135 |
clear: both; |
136 |
margin-top: 135px !important; |
137 |
}
|
138 |
|
139 |
.fname, .femail { |
140 |
width: 222px; |
141 |
float: left; |
142 |
}
|
143 |
|
144 |
form p { |
145 |
font-weight: bold; |
146 |
margin-bottom: 3px; |
147 |
}
|
148 |
|
149 |
form textarea { |
150 |
width: 365px; |
151 |
overflow: hidden; /* removes vertical scrollbar in IE */ |
152 |
}
|
153 |
|
154 |
form input, form textarea { |
155 |
background-color: #313d60; |
156 |
border: 1px solid #2d395c; |
157 |
color: #ffffff; |
158 |
padding: 5px; |
159 |
font-family: Lucida Sans Unicode, Helvetica, Arial, Verdana, sans-serif; |
160 |
margin-bottom: 10px; |
161 |
}
|



Conclusion
So there you have it! A great-looking, fully functional Shoutbox! You may have wondered what the point of creating a Shoutbox is, and well, you're right, there is no point. But what this does do is help give you some vital basic understanding of using PHP to work with a database, allowing you to move on to much more advanced guides here at NETTUTS.
Heck, you could even reuse this code to create yourself an incredibly basic blog! Not much point to it, but it's fun.