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


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
  • email
  • post
  • ipaddress

To create this, run the following SQL code. You will normally run this from the SQL tab in phpMyAdmin

Create Table

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. $host = ‘localhost’; //usually localhost
  2. $username = ‘root’; //your username assigned to your database
  3. $password = ‘password’; //your password assigned to your user & database
  4. $database = ‘shoutbox’; //your database name
  5. ?>

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.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shoutbox for NETTUTS by Dan Harper
<link rel="stylesheet" href="style.css" type="text/css" />
<div id="container">


  <h5><a href="" title="Dan Harper">Dan Harper </a> : <a href="" 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.

$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('

Unable to connect to the database server at this time.


mysql_select_db($database,$connect) or die('

Unable to connect to the database at this time.


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.

if(isset($_POST['send'])) {
    if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['post'])) {

You did not fill in a required field.

    } 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:

$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)) {

Thanks for shouting!

    } else {

There was an unexpected error when submitting your shout.


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.

$query = "SELECT * FROM `shouts` ORDER BY `id` DESC LIMIT 8;";

$result = @mysql_query("$query") or die('

There was an unexpected error grabbing shouts from the database.



    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
    while ($row = mysql_fetch_array($result)) {
        $ename = stripslashes($row['name']);
        $eemail = stripslashes($row['email']);
        $epost = stripslashes($row['post']);
        $grav_url = "".md5(strtolower($eemail))."&size=70"; 
  • Gravatar '.$ename.'
  • '); } ?>

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.

<form action="<?php $self ?>" method="post">
<h2>Shout! </h2>

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.

See more

karthikeyanPHPchat,php,shoutboxIntroduction 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,...PHP, HTML5, CSS, jQuery, Angular, Facebook Style Scripts & demos

Related Posts