DSwain- The New Day

Friday, November 24, 2006

A Basic PHP/MySQL Chat Room

Dedicated to Melissa (http://lyfaraurelor.blogspot.com/) because she dedicated an entry to me!

Ever have an issue where you wanted to set up a live chat type of system for your website? More than anything, ever have a computer class where you couldn't talk to people without getting into some type of trouble? Pretty sad, I know, so I decided to try and come up with a solution for it. Here's what I have, so far. This is also a fairly good demonstration of what I've been working on for my senior project. The actual project is not as simple as this little hack is by any means, but it uses a ton of similar things I have been using for the project.

Firstly, this isn't some type of new ground I'm charting here. It's been done in the past. It seems like that a lot of people have used PHP as the chatting system, but many of them use a text file to store the messages, which is commonly known as a flat file. Since all I have been doing programming wise is PHP and MySQL for the past several months, I figured I should just keep with the trend and use MySQL as opposed to a flat file. If you wish to use a flat file to set up a system like this, I recommend you check out this article on phpbuilder.com.

Anyway, the idea is fairly simple behind it. I created three functions (it probably could be reduced to two, or maybe none depending on how you program.) I generally like functions, so I ended up with three. The first one was to retrieve the messages from the database which I named getMessage(). The second is a function called postMessage() which takes the postdata from the HTML portion of the website and then queries it into the database table. Finally, I have a postForm() function which helps regenerate the actual table to post. It helps avoid using HTML built into the PHP file, but I don't see why doing that would be an issue either since that's one of its strongest points. I did it to attempt to not write header information, but that didn't work out. Either way should work fine for however you choose to do it.

1. getMessage(): This is what the code for the getMessage() function looks like
function getMessage() {
#Establish connection to DB
$connection = mysql_connect('localhost', 'mysql_web', 'dbpass');
$database = mysql_select_db('chat');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}

#Get the last messages
$query1 = 'select messages from messages order by id desc limit 0,15';
$result = mysql_query($query1);
$rowcount = mysql_num_rows($result);

while ($output_array = mysql_fetch_array($result)) {
for ($i = 0; $i <= $rowcount; $i++) {
echo "$output_array[$i]";
}
}
}


This is probably about as complex of a function you'll have in this program. First, you need to establish a connection to the database. Now, don't quote me on this one, but I establish the connection per function. I believe this is necessary, but I am not sure. If it isn't, then obviously just remove the connection code out of your functions and add them outside of it so it will be read each time the script is run. If anything, it will help make your code look more consistent than anything, which is always important. Then, you'll see the variable $query1. This is the actual SQL query that's performed on the DB/table to gather the information, If you want to keep it simple, you can just make the query something like "select messages from messages" and that should work just fine. The other options I have are "order by id desc" which basically instead of reading the DB from top to bottom, will read it from the bottom to the top. Obviously this is optional for however you want to display the data. The other thing I did was create a limit within the query. Initially, I was trying to force PHP to limit the output of the data, which it was not happy about. I eventually stumbled upon a query which limited the output of it, and it works like a charm. The next two variables are fairly less complex than the query itself. The first one performs the actual query with the query you throw at it, and the other variable counts the amount of rows within the table. While I could have avoided this part and hard coded my limit into it, this allows for it to be changed on-the-fly since I'll only have to update the query string if I want to display more entries. The final loop is a bit intense for those not familiar with PHP and MySQL. I know it was for me at first, but over the past two months or so, I've become quite adjusted to it. Here's the break down of it, though. I'll try and keep it short if I can help it... First, we have the while loop. Basically, this says that while the array $output_array is still gathering information from the query performed before, that it needs to execute the code below it. To get the actual data per entry from the query is mysql_fetch_array(mysql_query('some query')). The code I have looks much more clear than this because I made sure to use variables for everything. It's good to try and maintain the peace in sanity, if possible. Within the while statement is another loop that's occurring; a for loop. What's happening here is that first, it initializes a variable ($i in this instance. It could be anything though. $i is a common coding practice in for loops). The variable is equal to zero. The next part says that while the variable $i is less than $rowcount (the amount of rows queried from the DB) to execute a certain line of code below it and then increment $i by one. So what happens is that this for loop is constantly executed while the other loop is still able to gather data from the query. In turn, while this is occurring, it echo's (prints data out) the values it gathers from the query. Each time that the loop is executed, it will print out each new line of data, thanks to our $i variable which increases each time the loop is run. Luckily, that's about as complex as it gets in this script. My description of it is probably very poor, and in turn makes it seem confusing, but really it's a fairly straightforward piece of code. The last two functions are even easier to understand.

2. postMessage(): This is used to post the new entry into the DB

function postMessage() {
#Establish connection to DB
$connection = mysql_connect('localhost', 'mysql_web', 'dbpass');
$database = mysql_select_db('chat');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}

#Gather the data from the POST variable
$message = $_POST['message'];

#Query the data into the DB
$query = "insert into messages values ('$message
', NULL)";
$insert = mysql_query($query);
if (!$insert) {
die('Error:' . mysql_error());
}

flush();
}


Once again, we first initialize our DB connection. Then what happens is we create a variable $message. This variable is used to get the data from the HTML form which I'll explain in a moment. As an aside, you can use $_POST['message'] as the variable name, meaning you don't have to create a new variable for it, but it makes it rather clear so it's probably a good practice to have. After this, we have another query for the DB to execute. This time, we're performing an insert into the DB. Now, you may or may have not noticed that the values here include a "NULL" declaration. Basically, the deal with that is that in my database, there is an ID column which fills itself in (with numerical values) to keep track of each entry. Since we can't insert data into this column, we simply insert a "NULL" statement into the code and it avoids it. This query will change per your DB! So, if you try my script out, be sure to update all of the queries and whatnot to fit your DB. Also, you may have noticed the
code in the query string. I use this to provide spaces between each entry. If this wasn't done, then the text output would basically look like a jumbled mess. I may have also been able to avoid hard coding this
in and insert it into the loop now that I think about it, but either method works.

Finally, after all that, the query is executed and inserts the data into the database and then calls flush() to clear the buffers out.

3. postForm(). This is used to enter and submit the data.

*Sorry, it actually made HTML out of the code I posted. Check out the chat.txt file to see the code*

This is a little bit complex, but to give you the general idea, this creates a little text box, a button which says "Send" and a "Reload" button. This is where you would enter the data and then execute the postMessage() function. Overall this function is basically just some common HTML, with the exception of the $PHP_SELF variable. This simply gathers the name of the file which is being executed without the need to hard code it in. The rest of the string says for the script to execute the postMessage() function.

Since this entry is getting massive, I'll stop it here for now. If you wish to take a look at the code, here it is. Now also bare in mind, there is still a lot of stuff that this script could use. For example, an auto refresh system would be great to figure out. I've seen some done in Javascript, but I would like to avoid having to do that, if at all possible. I'm not exactly in the mood to learn another language just for one function, so if somebody wants to write that or another PHP function for it, by all means do and please share! A login/authentication system would be good to implement with this code also. I may very well do that soon, since the basics are now working like I want them to. I'm sure other features could be tacked onto it also.

That'll be enough for now. If you want to see my script in action though, you can see it here. Take it easy folks.

1 Comments:

  • Hi,
    I am interested in php/mysql script described by you for development of a chat application. But I am unable to download it from the URL provided by you. Can you please send it me on my email address pankaj@glug4muz.org so that I can study it carefully and then can implement in one of my project. I will remain thankful to you for this forever.

    Best Regards ...
    Pankaj Kumar

    By Anonymous Anonymous, at 11/30/2008 8:52 AM  

Post a Comment

<< Home