Building an AJAX-Based Chat: Interacting With a Database
In this third and final part of a tutorial that explains how to build an AJAX-based chat application, Alejandro Gervasio covers creating the PHP files that directly interact with a MySQL database, adding and fetching chat messages. He also makes some suggestions for expanding the functions of the application.
Building an AJAX-Based Chat: Interacting With a Database (Page 1 of 4 )
A downloadable file for this article is available here.
Here we are again. This is the concluding part of the series “Building an AJAX-based chat.” Welcome back. As you probably remember, developing an extensible chat application by using AJAX is not only a fairly easy task, but it’s also a fun experience. Stripped down to its bare bones, I implemented the driving logic of the chat by splitting the whole application into two different pieces of code. These are the “sender” and “receiver” modules respectively, which utilized two requester objects in order to handle independently http requests, for inserting new comments into the database and fetching chat messages.
Considering that the AJAX-based program is near to completion, the question is: what is next? Remember that from the very beginning of this series, I paid strong attention to writing all the code that runs on the browser, oriented to working with requester's objects, along with some simple PHP snippets. However, as you may have noticed, I didn’t get my hands into the complexities of creating the PHP files that directly interact with a MySQL database, handy for adding and fetching chat messages. Since I purposely left “untouched” the server PHP scripts for last, in this final article, I’ll code the required PHP files for accessing the database and handling messages.
Before I leap into writing down the PHP code, a brief clarification is in order: I’ll use a MySQL wrapping class for accessing the mentioned database, so all the sample files will use this class for running SQL queries and handling result sets. However, as you’ll see shortly, the code is flexible enough to be changed to work with a procedural method, in case you’re not familiar with an object-oriented approximation.
Having drawn the guidelines for this final tutorial, let’s get rid of the irrelevant details and start writing the server code for the chat application. Let’s go!