In this article, Tim will show you how to
create a quick-n-easy chat script using PHP and a very simple MySQL
database. The script will allow visitors to choose a nickname, enter
text to send to the chatting window, and view messages from other
people.
A MySQL Driven Chat Script In this article, Tim will show you how to create a quick-n-easy chat script using PHP and a very simple MySQL database. The script will allow visitors to choose a nickname, enter
text to send to the chatting window, and view messages from other
people... all in real-time! For a bit of fun, the chat application also
has buttons to send several emote-icons including smiling and frowning
faces.One of the most popular uses for the Internet is person-to-person
communication. There are many ways that we can communicate with each
other online including ICQ, MSN Messenger, forums, Email, mIRC and Java
chat applets. If you run a web site, then you should provide your
visitors with some sort of communication tool that will allow them to
express their opinions on a particular topic, as well as communicate
with other people sharing the same interests as them.
In this article, you will learn how to create a quick-n-easy chat script using PHP
and a very simple MySQL database. The script will run in a web browser
and the chats will be stored in a database. Our script will allow the
visitor to choose a nickname, enter text to “send” to the chatting
window, and view messages from other people… all in real-time! For a
bit of fun, our chat application will also have buttons to send several
emote-icons including smiling and frowning faces.
In this
article, I am assuming that you know how to create a MySQL database
from the command line. I will also assume that you have Apache, PHP and
MySQL on the same server running under Windows 2000. If you’re running
a Win9x/Unix box, don’t worry…everything is pretty much the same.
Firstly, let’s start by creating the database to store our chat sessions…
Creating the databaseEvery time a visitor logs in to our chat room, they choose a
nickname/alias. When they post a new message, it’s stored in a database
along with any other messages in that chat session. At any one time,
only the twenty most recent messages will be displayed in the chat
window. We will create a database named “chat”. The “chat” database
will contain just one table, named “chatScript”.
Start by typing “MySQL” at the command prompt to load the MySQL console app. Next, enter the commands shown below, each one separated by a new line:
create database chat;
create table chatScript
(
pk_Id int unsigned auto_increment,
theText varchar(100) not null,
theNick varchar(20) not null,
primary key(pk_Id),
unique id(pk_Id)
);
This
will create our chat database and table. The “pk_Id” field is simply an
auto-incrementing number, and will assign a new numerical id to each of
our chat messages when they are added to the database. The “theText”
field will contain the actual chat message posted by the user. The
“theNick” field will contain the nickname of the user posting the
message. Lastly, the “pk_Id” field is set as the primary key of the
chatScript table. It is also declared as a unique id, which stops us
from manually entering a duplicate value for the “pk_Id” field.
To
make sure our new chat database was created successfully and is
working, let’s try connecting to it through the MySQL console app and
inserting a record into the chatScript table, like this:
connect chat;
insert into chatScript values(0, 'This is a test message', 'TestUser');
That’s
all there is to creating the database for our chat application. Now
let’s look at creating the PHP script which will allow our visitors to
login and post messages.
The chat script explained Our chat script will be created as only one file, named “chat.php”.
It will contain four functions named ShowLoginForm, Login, GetInput and
ShowAddPosts. These four functions are described below.
The ShowLoginForm function
The
ShowLoginForm function is called whenever a visitor loads our chat.php
script for the first time. It will display a HTML form that contains a
field for the user to enter their nickname into. Once this form is
submitted, the Login function is called.
The code for the ShowLogin function looks like this:
function ShowLoginForm() {
?>
Enter Your NickName
}
The output from the ShowLogin function looks like this:

The Login function
The
login function is responsible for taking the users nickname (which is
passed to the function from the login form created by the ShowLoginForm
function) and creating a new session variable from it. This session
variable will allow our chat script to track the user throughout their
entire chat session, until they close their browser window. The login
function also displays the actual frames for the chat page, by using
one HTML tag and two tags. The code for
the Login function is shown below:
function Login() {
global $chat;
global $nick;
session_start();
session_register("nick", $nick);
?>
This page uses frames, but your browser doesn't support them.
}
The
tag creates two horizontal frames: The first (the main
chat window, which will display the messages) is 563 pixels high. The
second (which will allow the visitor to enter their message) is 62
pixels high. Pay careful attention to the “src” attribute of the two
tags. You will notice that they pass an “action” value,
as well as the users nickname as part of the URL’s query string. We
will talk more about this in just a minute.
The output from the Login function looks like this:

Remember
how we added a test record to the “chatscript” table when we were
creating it? If you take a look at the screen shot above, you can see
that it appears in the contents of our main chat window. The actual
contents of the top and bottom frames shown above are generated by the
GetInput and ShowAddPosts functions. They are described below.
The GetInput function
This
function is responsible for generating the bottom frame of our chat
window, and allows the user to enter their message in a text box and
send it. If you look at the screen shot shown above, you will also see
that the bottom frame contains a “Say” button (to submit the message),
a color drop-down list (this lets the visitor choose the color of their
message), and several icon-icon buttons.
When we press enter in
the text field, or click on the “Say” button, the JavaScript function
“doSubmit” is called. This function will make sure that the visitor has
actually entered a message. If they have, then the function will get
the currently selected color from the drop-down list, and change the
value of the text field so that it’s surrounded by and
tags. The function will return true, and our form is
submitted. If the text field is empty, the browser displays a message
box kindly asking the user to enter a message and returns false,
stopping the form from being submitted. The code for the “doSubmit”
function is shown below:
function doSubmit()
{
if(document.chatform.chat.value == '') {
alert('Please enter some text!');
document.chatform.chat.focus();
return false;
}
document.chatform.chat.value = ''+document.chatform.chat.value+'';
document.chatform.submit();
document.chatform.chat.value = '';
document.chatform.chat.focus();
return true;
}
When
one of the icon-icon buttons is pressed, the form will call the
sendFace JavaScript function, which will automatically send either
“:)”, “:(”, or “:D” to the top frame of our chat window. When the top
frame receives either of these, the ShowAddPosts function will
automatically display an image corresponding to that icon-icon, instead
of the “:)”. So, for example, if we entered “:)” in the text field or
clicked on the “:)” button, the top frame would display the appropriate
icon-icon image, like this:

The
images for the icons-icons are included as part of the support material
at the end of this article, and should be saved in the same directory
as the chat.php script (which is also included as part of the support material).
The code for the entire GetInput function is shown below:
function GetInput() {
global $HTTP_SESSION_VARS;
global $chat;
global $nick;
?>
Black
Red
Green
Blue
Orange
function sendFace(faceNum)
{
switch(faceNum)
{
case 1:
document.chatform.chat.value = ':)';
break;
case 2:
document.chatform.chat.value = ':(';
break;
case 3:
document.chatform.chat.value = ':D';
break;
}
document.chatform.submit();
document.chatform.chat.value = '';
}
function doSubmit()
{
if(document.chatform.chat.value == '') {
alert('Please enter some text!');
document.chatform.chat.focus();
return false;
}
document.chatform.chat.value = ''+document.chatform.chat.value+'';
document.chatform.submit();
document.chatform.chat.value = '';
document.chatform.chat.focus();
return true;
}
}
The ShowAddPosts function
This is the most important function of the entire chat script, and is
responsible for adding new messages to the database as well as display
the last twenty messages posted. Firstly, the ShowAddPosts function
declares the $chat and $nick variables as global. This will give us
access to the message being posted (if any), as well as the users
nickname, which is stored as a session variable:
global $HTTP_SESSION_VARS;
global $chat;
global $nick;
To
make sure our visitor sees all of the newest messages, we add a
tag to the HTML page, which will cause it to refresh
itself every ten seconds:
print 'php?action=posts&nick=">';
Then
we create a connection to the “chat” database and select the
“chatScript” table. The results of these functions are stored in the
$svrConn and $dbConn variables respectively:
$svrConn = mysql_connect("localhost", "admin", "password") or die("Error: Couldnt connect to database");
$dbConn = mysql_select_db("chat", $svrConn) or die ("Error: Couldnt connect to database");
You
should change the value of “admin” to a valid username for your
database. Also, change the value of “password” to a valid password for
your database.
Next, the script checks to see whether or not the
user is posting a message. If he/she is, then the $chat variable will
hold the message. The $chat variable is automatically created by PHP
from the form element, which is
where we enter the message. An SQL query is executed, which inserts the
new message into the database:
if(!empty($chat)) {
$strQuery = "insert into chatScript values(0, '$chat', '$nick')";
mysql_query($strQuery);
}
Once
the new message is inserted into the database, we run a SELECT query to
get the twenty most recent posts, which will be ordered based on the
“pk_Id’ field in descending order:
$strQuery = "select theText, theNick from chatScript order by pk_Id desc limit 20";
$chats = mysql_query($strQuery);
The
$chats variable will contain the result of the SQL query. We simply
loop through those results, displaying each record one at a time:
while($chatline = mysql_fetch_array($chats)) {
print "" . $chatline["theNick"] . ": " . swapFaces($chatline["theText"]) . "
";
}
The
actual message is passed to the “swapFaces” function, which replaces
“:)”, “:(“ and “:D” with an tag to display the
corresponding image for that icon-icon. The swapFaces function looks
like this:
function swapFaces($chatLine) {
$chatLine = str_replace(":)", " ", $chatLine);
$chatLine = str_replace(":(", " ", $chatLine);
$chatLine = str_replace(":D", " ", $chatLine);
return $chatLine;
}
One
last thing to mention is that each time a form is submitted, a hidden
field named “action” is also passed along with it. This tells the PHP
script which function to call. We use an if…else control to redirect
our script to the appropriate function, like this:
if (empty($action))
ShowLoginForm();
elseif ($action == "posts")
ShowAddPosts();
elseif ($action == "form")
GetInput();
elseif ($action == "enter")
Login();
That’s
the code for our simple chat script explained. Take a look at the
screen shot below (it shows me and two of my friends conversing over
nothing):
Conclusion
Creating and promoting visitor interaction on your site doesn’t have to
take a lot of time or cost a lot of money! The chat script we have just
created can act as a great base onto which you can build a complete web
based chat application. Here are some ideas to improve the performance
of our chat script:
- Show a list of the people currently using
the chat. Add a logout button, another frame, and another table to the
database. When they login, add a record of their name to the new table.
When they logout, remove their name from the table. Inside of the new
frame, simply use a SELECT query to list all of the people currently
using the chat script. Add a tag to the frame to make it
refresh every 30 seconds.
- Allow users to private message each other.
- Add more icons-icons and allow visitors to send images as part of their message (just get the URL of the image from them).
- Let the visitors create groups. Each group can contain more than one channel, which is an instance of a chat session.
- Whenever
a URL is typed into the text box (such as http://www.devarticles.com),
make the top frame automatically display it as a hyperlink.
Also,
be sure to take a look at some of the links below if you’re after more
information on creating an online chatting application. If you want to
get serious and learn more about PHP or MySQL, I would recommend the
books shown below.
Until next time, I hope you enjoy playing
around with the chat application. Remember you can download the SQL
script, source code and images by clicking on the “supporting material”
link below.
|