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.
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.
You should receive a "Your SQL query has been executed successfully" message
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.
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:
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.
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:
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.
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.
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.
Heck, you could even reuse this code to create yourself an incredibly basic blog! Not much point to it, but it's fun.
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
- id
- name
- post
- ipaddress
1
2
3
4
5
6
7
8
| CREATE TABLE `shouts` ( `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, ` name ` VARCHAR (45) NOT NULL , `email` VARCHAR (60) NOT NULL , `post` TEXT NOT NULL , `ipaddress` VARCHAR (45) NOT NULL , PRIMARY KEY (`id`) ); |
The Files
We will need three files created for this project:- index.php
- style.css
- db.php
Database Connection Details
The db.php file will be used to store our database details. Open it and insert the following code:
1
2
3
4
5
6
| <?php $host = 'localhost' ; //usually localhost $username = 'root' ; //your username assigned to your database $password = 'password' ; //your password assigned to your user & database $database = 'shoutbox' ; //your database name ?> |
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.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
| <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> < head > < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> < title >Shoutbox for NETTUTS by Dan Harper</ title > < link rel = "stylesheet" href = "style.css" type = "text/css" /> </ head > < body > < div id = "container" > < h1 >Shoutbox</ h1 > < 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 > < div id = "boxtop" /> < 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
3
4
5
6
7
8
| <?php $self = $_SERVER [ 'PHP_SELF' ]; //the $self variable equals this file $ipaddress = ( "$_SERVER[REMOTE_ADDR]" ); //the $ipaddress var equals users IP include ( 'db.php' ); // for db details $connect = mysql_connect( $host , $username , $password ) or die ( '<p class="error">Unable to connect to the database server at this time.</p>' ); mysql_select_db( $database , $connect ) or die ( '<p class="error">Unable to connect to the database at this time.</p>' ); |
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
3
4
| if (isset( $_POST [ 'send' ])) { if ( empty ( $_POST [ 'name' ]) || empty ( $_POST [ 'email' ]) || empty ( $_POST [ 'post' ])) { echo ( '<p class="error">You did not fill in a required field.</p>' ); } else { |
Otherwise, we continue:
01
02
03
04
05
06
07
08
09
10
11
12
13
| $name = htmlspecialchars(mysql_real_escape_string( $_POST [ 'name' ])); $email = htmlspecialchars(mysql_real_escape_string( $_POST [ 'email' ])); $post = htmlspecialchars(mysql_real_escape_string( $_POST [ 'post' ])); $sql = "INSERT INTO shouts SET name='$name', email='$email', post='$post', ipaddress='$ipaddress';" ; if (@mysql_query( $sql )) { echo ( '<p class="success">Thanks for shouting!</p>' ); } else { echo ( '<p class="error">There was an unexpected error when submitting your shout.</p>' ); } } } |
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
3
4
5
| $query = "SELECT * FROM `shouts` ORDER BY `id` DESC LIMIT 8;" ; $result = @mysql_query( "$query" ) or die ( '<p class="error">There was an unexpected error grabbing shouts from the database.</p>' ); ?><ul><? |
On the second line we execute the query and store it in $result. We now:
01
02
03
04
05
06
07
08
09
10
11
12
13
| while ( $row = mysql_fetch_array( $result )) { $ename = stripslashes ( $row [ 'name' ]); $eemail = stripslashes ( $row [ 'email' ]); $epost = stripslashes ( $row [ 'post' ]); echo ( '<li><div class="meta"><img src="' . $grav_url .'" alt= "Gravatar" /> <p> '.$ename.' </p></div><div class = "shout" ><p> '.$epost.' </p></div></li>'); } ?></ul> |
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.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
| < form action="<?php $self ?>" method="post"> < h2 >Shout! </ h2 > < div class = "fname" >< label for = "name" >< p >Name:</ p ></ label >< input name = "name" type = "text" cols = "20" /></ div > < div class = "femail" >< label for = "email" >< p >Email:</ p ></ label >< input name = "email" type = "text" cols = "20" /></ div > < textarea name = "post" rows = "5" cols = "40" ></ textarea > < input name = "send" type = "hidden" /> < p >< input type = "submit" value = "send" /></ p > </ form > </ div > <!--/content--> < div id = "boxbot" ></ div > </ div > <!--/container--> </ body > </ html > |
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.
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
| * { margin : 0 ; padding : 0 ; } body { background : #323f66 top center url ( "images/back.png" ) no-repeat ; color : #ffffff ; font-family : Helvetica , Arial , Verdana , sans-serif ; } h 1 { font-size : 3.5em ; letter-spacing : -1px ; background : url ( "images/shoutbox.png" ) no-repeat ; width : 303px ; margin : 0 auto ; text-indent : -9999em ; color : #33ccff ; } h 2 { font-size : 2em ; letter-spacing : -1px ; background : url ( "images/shout.png" ) no-repeat ; width : 119px ; text-indent : -9999em ; color : #33ccff ; clear : both ; margin : 15px 0 ; } h 5 a:link, h 5 a:visited { color : #ffffff ; text-decoration : none ; } h 5 a:hover, h 5 a:active, h 5 a:focus { border-bottom : 1px solid #fff ; } p { font-size : 0.9em ; line-height : 1.3em ; font-family : Lucida Sans Unicode, Helvetica , Arial , Verdana , sans-serif ; } p.error { background-color : #603131 ; border : 1px solid #5c2d2d ; width : 260px ; padding : 10px ; margin-bottom : 15px ; } p.success { background-color : #313d60 ; border : 1px solid #2d395c ; width : 260px ; padding : 10px ; margin-bottom : 15px ; } #container { width : 664px ; margin : 20px auto ; text-align : center ; } #boxtop { margin : 30px auto 0px ; background : url ( "images/top.png" ) no-repeat ; width : 663px ; height : 23px ; } #boxbot { margin : 0px auto 30px ; background : url ( "images/bot.png" ) no-repeat ; width : 664px ; height : 25px ; } #content { margin : 0 auto ; width : 664px ; text-align : left ; background : url ( "images/bg.png" ) repeat-y ; padding : 15px 35px ; } #content ul { margin-left : 0 ; margin-bottom : 15px ; } #content ul li { list-style : none ; clear : both ; padding-top : 30px ; } #content ul li:first-child { padding-top : 0 ; } .meta { width : 85px ; text-align : left ; float : left ; min-height : 110px ; font-weight : bold ; } .meta img { padding : 5px ; background-color : #313d60 ; } .meta p { font-size : 0.8em ; } .shout { width : 500px ; float : left ; margin-left : 15px ; min-height : 110px ; padding-top : 5px ; } form { clear : both ; margin-top : 135px !important ; } .fname, .femail { width : 222px ; float : left ; } form p { font-weight : bold ; margin-bottom : 3px ; } form textarea { width : 365px ; overflow : hidden ; /* removes vertical scrollbar in IE */ } form input, form textarea { background-color : #313d60 ; border : 1px solid #2d395c ; color : #ffffff ; padding : 5px ; font-family : Lucida Sans Unicode, Helvetica , Arial , Verdana , sans-serif ; margin-bottom : 10px ; } |
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.
No comments:
Post a Comment