XML
  Home arrow XML arrow Page 2 - Building an AJAX-Based Chat: Interacting W...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
XML

Building an AJAX-Based Chat: Interacting With a Database
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 32
    2005-11-21

    Table of Contents:
  • Building an AJAX-Based Chat: Interacting With a Database
  • Adding messages to the database: looking at the “sendchatdata.php” file
  • Reading messages from the server: defining the “getchatdata.php” file
  • Putting the files together: the complete chat application at a glance

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Building an AJAX-Based Chat: Interacting With a Database - Adding messages to the database: looking at the “sendchatdata.php” file


    (Page 2 of 4 )

    As I said previously, before I start coding the pertinent PHP files for accessing the database, first allow me to list the corresponding MySQL wrapping class, which I plan to use within the PHP scripts. Here is how it looks:

    class MySQL{
        var $conId; // connection identifier
        var $host; // MySQL host
        var $user; // MySQL username
        var $password; // MySQL password
        var $database; // MySQL database
        var $result; // MySQL result set
        // constructor
        function MySQL($options=array()){
            // validate incoming parameters
            if(count($options)<1){
                trigger_error('No connection
    parameters were provided');
                exit();
            }
            foreach($options as $parameter=>$value){
                if(!$parameter||!$value){
                    trigger_error('Invalid
    connection parameter');
                    exit();
                }
                $this->{$parameter}=$value;
            }
            // connect to MySQL
            $this->connectDB();
        }
        // connect to MYSQL server and select
    database
        function connectDB(){
            if(!$this->conId=mysql_connect($this-
    >host,$this->user,$this->password)){
                trigger_error('Error connecting to
    the server '.mysql_error());
                exit();
            }
            if(!mysql_select_db($this-
    >database,$this->conId)){
     trigger_error('Error selecting database '.mysql_error());
     exit();
            }
        }
        // perform query
        function query($query){
            if(!$this->result=mysql_query
    ($query,$this->conId)){
     trigger_error('Error performing query
    '.$query.' '.mysql_error());
     exit();
            }
        }
        // fetch row
        function fetchRow(){
            return mysql_fetch_array($this-
    >result,MYSQL_ASSOC);
        }
        // count rows
        function countRows(){
            if(!$rows=mysql_num_rows($this-
    >result)){
     trigger_error('Error counting rows');
     exit();
            }
            return $rows;
        }
        // count affected rows
        function countAffectedRows(){
            if(!$rows=mysql_affected_rows($this-
    >conId)){
     trigger_error('Error counting affected rows');
     exit();
            }
            return $rows;
        }
        // get ID from last inserted row
        function getInsertID(){
            if(!$id=mysql_insert_id($this->conId)){
     trigger_error('Error getting ID');
     exit();
            }
            return $id;
        }
        // seek row
        function seekRow($row=0){
            if(!mysql_data_seek($this-
    >result,$row)){
     trigger_error('Error seeking data');
     exit();
            }
        }
    }

    Although I’ll use only the “query()” and “getInsertID()” methods of the above MySQL class, having an idea of how the whole class looks makes it easier to understand the logic behind the corresponding PHP files. In simple terms, the first file “sendchatdata.php” will connect to the database, then obtain the message submitted by the user, along with his/her nickname, and finally insert the data into a single table. In order to keep things simple, the structure of the database table will be defined by an ID field (the primary key), and a string “message” field, useful for storing chat messages. As you can see, the schema is extremely understandable.

    Once a message is added to the database table, the script will fetch the last twenty messages, and send them out directly to the client. Certainly, I’ve chosen arbitrarily the number of messages to be retrieved, but this parameter can be easily changed to meet particular needs.

    Now that you know how chat messages will be fetched from the database table, below is the definition for the “sendchatdata.php” file:

    // include class file
    require_once 'mysql_class.php';
    // connect to MySQL
    $db=&new MySQL(array('host'=>'host','user'=>'user',
    'password'=>'password','database'=>'chat'));
    // get user & message
    $user=$_POST['user'];
    $message=$_POST['message'];
    // insert new message into database table
    $db->query("INSERT INTO messages SET user='$user',message='$message'");
    // get ID from last inserted message
    $id=$db->getInsertID();
    // delete messages when ID > 1000
    if($id>1000){
        $db->query("DELETE FROM messages WHERE id <
    ($id-10)");
    }
    // retrieve last 20 messages
    $db->query("SELECT user,message FROM messages
    WHERE id <=$id ORDER BY id DESC LIMIT 20");
    // send messages to the client
    while($row=$db->fetchRow()){
     echo '<'.$row['user'].'>'.$row['message'].'|';
    }

    As shown above, the file uses the MySQL wrapping class for connecting to the database, inserting a new message together with the chosen nickname, and lastly fetching the last twenty messages. The final “while” loop is responsible for echoing the data, so it can be grasped within the JavaScript application by the “responseText” property belonging to the proper XMLHttpRequest object. Please note how basic formatting is applied to the data, and how each table row is separated by a pipe character (“|”), so it can be processed as an array structure.

    The last thing to be noted is the addition of the following checking line:

    if($id>1000){
        $db->query("DELETE FROM messages WHERE id <
    ($id-10)");
    }

    Essentially, the task of this line is to clean up the messages table by deleting most of them, when the table contains more than 1,000 messages. Again, this parameter is optional and configurable, so you can change it, in order to suit your specific requirements.

    Having defined the first PHP file, which inserts and fetches chat messages from the database table, it’s time to move forward, in order to write the second server script, responsible for reading user messages. So, let’s jump straight into the next section and see how this is done.

    More XML Articles
    More By Alejandro Gervasio


       · This last article of the series goes through the development of the PHP scripts...
       · Great article, thanks!
       · Thank you for the compliments on my AJAX article.Regards.
       · Hi Alejandro,again a really interesting article. Thanks a lot!One question...
       · Hello again,Thank you for the positive comments on my article. Comming to your...
       · Thanks for your quick reply Alejandro. And good to get your confirmation that it...
       · Hello Matthijs,I'd like to thank you for reading the tutorial. Good...
       · Hi Alejandro! Thank you very much for your great AJAX chat tutorial. It has helped...
       · I solved it! I just added to the sendMessage function:...
       · Fantastic article you've really helped me to understand.But I have a question...
       · As posted earlier by someone else, when pressing return on a message, it does not...
       · Thanks a lot for your comments on the article. Also, I'm glad to know that you found...
       · Hello,Thanks for reading my article. Regarding your question, that happens...
       · Thank you for your comments. With reference to your question, you should modify the...
       · Create a new function:function submitSend(){ ...
       · Thank you for submitting your feedback on this article. Yeap, creating a function...
       · the article by Alejandro Gervasio is really brilliant, it worked first time, and it...
       · Thank you for your compliments on my AJAX article, since they're very welcome. I'm...
       · Your tip worked for me in Firefox. But in IE I still couldn't use the enter key. I...
       · Thank you for your feedback. Also, it's good to hear that my suggestion worked for...
       · Hello!First of all, congratulations for the great article. It really helped me...
       · Hello Lucas,Thank you for your kind comments on my article. I've tested the chat...
       · Hi guys!I created a control that works like an AJAX container. Basically the way it...
       · Thanks a lot for posting your comments here. Even when I'm not well versed on...
       · Thank you very much for your explanation. I wouldn't say that I understand...
       · Hi again,Sorry to hear that the http headers didn't solve your problem. However...
       · hey sorry for the inconvencience...but after a while I got the chatfunction to...
       · Hello,Good to know that the http headers now worked for you. Concerning your...
       · Hello, Sorry it's me again.I'm working on a online/offline function. I have one...
       · Hello again,It's good to see the way that you redefined the structure of the...
       · Well that's the problem.. if I for instance would use this code:function...
       · Hello again,I see you're still in problems, but there's one thing that came up...
       · Well thanks for you help.. And your idea is a good one.. But i figured out what...
       · Hi again,I'm glad to know you figured out how to solve the problem. Good luck...
       · I have been trying to implement smilies, but whenever i convert certain char strings...
       · Thanks for the comment on my AJAX article. Concerning your question, you should...
       · Thanks! it worked great.However after implementing this code the name no longer...
       · I'm glad to know the suggestions I made previously worked for you concerning the...
       · strangely enough the...
       · Hello,Please check the above post, in order to get an idea on how to include...
       · Thank you for your well organized and refreshing explanation of a simple Ajax...
       · Hello Bob,First off, I’d like to thank you for your kind comments on my AJAX...
       · Found the article fantastic. Very insightful. Was wondering if one could easily...
       · Thanks for the kind words on my Ajax article. Regarding your question, a current...
     

    XML ARTICLES

    - Datatypes and More in RELAX NG
    - Providing Options in RELAX NG
    - An Introduction to RELAX NG
    - Path, Predicates, and XQuery
    - Using Predicates with XQuery
    - Navigating Input Documents Using Paths
    - XML Basics
    - Introduction to XPath
    - Simple Web Syndication with RSS 2.0
    - Java UI Design with an IDE
    - UI Design with Java and XML Toolkits
    - Displaying ADO Retrieved Data with XML Islan...
    - Widget Walkthrough
    - Introduction to Widgets
    - The Why and How of XML Data Islands







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway