Home arrow MySQL arrow Page 5 - A MySQL Driven Chat Script

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.

Author Info:
By: Tim Pabst
Rating: 4 stars4 stars4 stars4 stars4 stars / 285
December 25, 2001
  1. · A MySQL Driven Chat Script
  2. · Creating the database
  3. · The chat script explained
  4. · The chat script explained (contd.)
  5. · The chat script explained (contd.)
  6. · Conclusion

print this article

A MySQL Driven Chat Script - The chat script explained (contd.)
(Page 5 of 6 )

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 $chat;

global $nick;

To make sure our visitor sees all of the newest messages, we add a <meta> tag to the HTML page, which will cause it to refresh itself every ten seconds:

print '<meta http-equiv="refresh" content="10;URL=chat.php?action=posts&nick=<?php echo $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("<b>Error:</b> Couldnt connect to database");

$dbConn = mysql_select_db("chat", $svrConn) or die ("<b>Error:</b> 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 <input type=”text” name=”chat”> 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')";



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 "<b>" . $chatline["theNick"] . ":</b> " . swapFaces($chatline["theText"]) . "<br>";


The actual message is passed to the “swapFaces” function, which replaces “:)”, “:(“ and “:D” with an <img> tag to display the corresponding image for that icon-icon. The swapFaces function looks like this:

function swapFaces($chatLine) {

$chatLine = str_replace(":)", "<img src='smile.gif'>", $chatLine);

$chatLine = str_replace(":(", "<img src='frown.gif'>", $chatLine);

$chatLine = str_replace(":D", "<img src='bigsmile.gif'>", $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))


elseif ($action == "posts")


elseif ($action == "form")


elseif ($action == "enter")


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

Our simple chat script in action!
blog comments powered by Disqus

- MySQL and BLOBs
- Two Lessons in ASP and MySQL
- Lord Of The Strings Part 2
- Lord Of The Strings Part 1
- Importing Data into MySQL with Navicat
- Building a Sustainable Web Site
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- PhpED 3.2 – More Features Than You Can Poke ...
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- Security and Sessions in PHP
- Setup Your Personal Reminder System Using PHP
- Create a IP-Country Database Using PERL and ...
- Developing a Dynamic Document Search in PHP ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials