Sei sulla pagina 1di 12

Dev Articles

05/06/2005 07:49:27 PM

MySQL
A MySQL Driven Chat Script Contributed by Tim Pabst 20011225 [ Send Me Similar Content When Posted ] [ Add Developer Shed Headlines To Your Site ]

DISCUSS

NEWS

SEND

PRINT

PDF

Article this article, Tim will show you how to create a quickneasy chat script using PHP and a very simple MySQL databas In Index: 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 realtime! For a bit of fun, the chat application also has buttons to send several emoteicons includin smiling and frowning faces.One of the most popular uses for the Internet is persontoperson 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, Im going to show you how to create a quickneasy 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 t choose a nickname, enter text to send to the chatting window, and view messages from other people all in realtime! For a bit of fun, our chat application will also have buttons to send several emoteicons 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 youre running a Win9x/Un box, dont worryeverything is pretty much the same.

Firstly, lets start by creating the database to store our chat sessions Every time a visitor logs in to our chat room, they choose a nickname/alias. When they post a new message, its 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 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;

1/12

Dev Articles 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) );

05/06/2005 07:49:27 PM

This will create our chat database and table. The pk_Id field is simply an autoincrementing 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, lets try connecting to it through the MySQ 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'); Thats all there is to creating the database for our chat application. Now lets look at creating the PHP script which will allow our visitors to login and post messages. 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() { ?> <b>Enter Your NickName</b> <form name="chat" method="post" action="chat.php" target="_top"> <input type="text" name="nick" size="20"> 2/12

Dev Articles <input type="hidden" name="action" value="enter">

05/06/2005 07:49:27 PM

<input type="hidden" name="chat" value="<font color=FF0000><b>Enters the Room</b></font>"> <input type="submit" name="Submit" value="Submit"> </form> <?php } 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 create 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 <frameset> HTML tag and two <FRAME> tags. The code for th Login function is shown below: function Login() { global $chat; global $nick;

session_start(); session_register("nick", $nick);

3/12

Dev Articles ?> <frameset rows="563,62" cols="*">

05/06/2005 07:49:27 PM

<frame name="posts" src="chat.php?action=posts?php echo $nick; ?>?php echo $chat; ?>"> <frame name="form" src="chat.php?action=form?php echo $nick; ?>"> </frameset> <noframes> <body> <p>This page uses frames, but your browser doesn't support them.</p> </body> </noframes> </frameset> <?php }

The <frameset> 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 <frame> tags. You will notice that they pass an action value, as well as the users nickname as part of the URLs query string. We will talk more about this in just a minute. The output from the Login function looks like this:

4/12

Dev Articles

05/06/2005 07:49:27 PM

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 GetInp function

This function is responsible for generating the bottom frame of our chat window, and allows the user to enter their messag 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 dropdown list (this lets the visitor choose the color of their message), and several iconicon 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 currentl selected color from the dropdown list, and change the value of the text field so that its surrounded by <font> and </font tags. The function will return true, and our form is submitted. If the text field is empty, the browser displays a message bo 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!');

5/12

Dev Articles document.chatform.chat.focus(); return false; }

05/06/2005 07:49:27 PM

document.chatform.chat.value = '<font color="'+document.chatform.col[document.chatform.col.selectedIndex].text+'">'+document.chatform.chat.value+'</font> document.chatform.submit(); document.chatform.chat.value = ''; document.chatform.chat.focus(); return true; }

When one of the iconicon buttons is pressed, the form will call the sendFace JavaScript function, which will automatical 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 iconicon, 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 iconicon image, like this:

6/12

Dev Articles

05/06/2005 07:49:27 PM

The images for the iconsicons are included as part of the support material at the end of this article, and should be saved i 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; ?>

<form onSubmit="return doSubmit" name="chatform" method="post" action="chat.php" target="posts"> <input type="text" name="chat"> <input type="hidden" name="nick" value="<?php echo $nick; ?>"> <input type="button" onClick="doSubmit()" name="Submit" value="Say"> <select name="col"> <option>Black</option> <option>Red</option> <option>Green</option> <option>Blue</option> <option>Orange</option> </select>

<input type="button" name="DoFace1" value=" :) " onClick="sendFace(1)"> <input type="button" name="DoFace2" value=" :( " onClick="sendFace(2)"> <input type="button" name="DoFace3" value=" :D " onClick="sendFace(3)"> <input type="hidden" name="action" value="posts"> </form>

7/12

Dev Articles <script language="JavaScript"> 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; }

05/06/2005 07:49:27 PM

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; } 8/12

Dev Articles

05/06/2005 07:49:27 PM

document.chatform.chat.value = '<font color="'+document.chatform.col[document.chatform.col.selectedIndex].text+'">'+document.chatform.chat.value+'</font> document.chatform.submit(); document.chatform.chat.value = ''; document.chatform.chat.focus(); return true; } </script> <?php } 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 variable 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 <meta> tag to the HTML page, which will cause it to refresh itself every ten seconds: print '<meta httpequiv="refresh" content="10;URL=chat.php?action=posts?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 th 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: 9/12

Dev Articles if(!empty($chat)) { $strQuery = "insert into chatScript values(0, '$chat', '$nick')"; mysql_query($strQuery); }

05/06/2005 07:49:27 PM

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 iconicon. 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 ifelse control to redirect our script to the appropriate functio like this: if (empty($action)) ShowLoginForm(); elseif ($action == "posts") ShowAddPosts(); 10/12

Dev Articles elseif ($action == "form") GetInput(); elseif ($action == "enter") Login();

05/06/2005 07:49:27 PM

Thats 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): Creating and promoting visitor interaction

on your site doesnt have to take a lot of time or cost a lot of money! The chat script we have just created can act as a grea base onto which you can build a complete web based chat application. Here are some ideas to improve the performance o 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 fro 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 <meta> tag to the frame to make it refresh every 30 seconds. Allow users to private message each other. 11/12

Dev Articles

05/06/2005 07:49:27 PM

Add more iconsicons 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 automatica display it as a hyperlink.

Also, be sure to take a look at some of the links below if youre 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.

12/12

Potrebbero piacerti anche