Jump to content

Simple Chat system using PHP, MySQL and Ajax

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
Csabi

Csabi

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
In this tutorial I will show you how to create a simple but <b>very</b> effective Chat script, and I said effective because unlike the most of the chat scripts this one deletes automatically the old messages from the database. Here is a live demo:
PHP Chat system

The chat system is made of 4 files:
create-table.php
<?php 

//Connect to MySQL

mysql_connect('host', 'database', 'password')

or die (mysql_error());

//Select database

mysql_select_db('database')

or die (mysql_error());

//Create the table

mysql_query("create table chat(

   time int(11) NOT NULL, 

   name varchar(30) NOT NULL, 

   ip varchar(15) NOT NULL, 

   message varchar(255) NOT NULL, 

   PRIMARY KEY (time)

)") or die (mysql_error());

echo "Complete.";

?>

chat.php
<html>

<head>

<style>

.message {

   overflow:hidden;

   width:498px;

   margin-bottom:5px;

   border:1px solid #999;

}

.messagehead {

   overflow:hidden;

   background:#FFC;

   width:500px;

}

.messagecontent {

   overflow:hidden;

   width:496px;

}

</style>

</head>


<body>

<div id="chat" style="width:500px;margin:0 auto;overflow:hidden;">

//This div will contain the messages

<div id="messages"></div>

//This div will contain an eventual error message

<div id="error" style="width:500px;text-align:center;color:red;"></div>

//This div contains the forms and the send button

<div id="write" style="text-align:center;"><textarea id="message" cols="50" rows="5"></textarea><br/>Name:<input type="text" id="name"/><input type="button" value="Send" onClick="send();"/></div>

</div>


<script type="text/javascript">

//This function will display the messages

function showmessages(){

   //Send an XMLHttpRequest to the 'show-message.php' file

   if(window.XMLHttpRequest){

      xmlhttp = new XMLHttpRequest();

      xmlhttp.open("GET","show-messages.php",false);

      xmlhttp.send(null);

   }

   else{

      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

      xmlhttp.open("GET","showmessages.php",false);

      xmlhttp.send();

   }

   //Replace the content of the messages with the response from the 'show-messages.php' file

   document.getElementById('messages').innerHTML = xmlhttp.responseText;

   //Repeat the function each 30 seconds

   setTimeout('showmessages()',30000);

}

//Start the showmessages() function

showmessages();

//This function will submit the message

function send(){

   //Send an XMLHttpRequest to the 'send.php' file with all the required informations

   var sendto = 'send.php?message=' + document.getElementById('message').value + '&name=' + document.getElementById('name').value;

   if(window.XMLHttpRequest){

      xmlhttp = new XMLHttpRequest();

      xmlhttp.open("GET",sendto,false);

      xmlhttp.send(null);

   }

   else{

      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

      xmlhttp.open("GET",sendto,false);

      xmlhttp.send();

   }

   var error = '';

   //If an error occurs the 'send.php' file send`s the number of the error and based on that number a message is displayed

   switch(parseInt(xmlhttp.responseText)){

   case 1:

      error = 'The database is down!';

      break;

   case 2:

      error = 'The database is down!';

      break;

   case 3:

      error = 'Don`t forget the message!';

      break;

   case 4:

      error = 'The message is too long!';

      break;

   case 5:

      error = 'Don`t forget the name!';

      break;

   case 6:

      error = 'The name is too long!';

      break;

   case 7:

      error = 'This name is already used by somebody else!';

      break;

   case 8:

      error = 'The database is down!';

   }

   if(error == ''){

      document.getElementById('error').innerHTML = '';

      showmessages();

   }

   else{

      document.getElementById('error').innerHTML = error;

   }

}

</script>


</body>

</html>

send.php
<?php

//Connect to MySQL

mysql_connect('host', 'database', 'password') or die (1);

//Select database

mysql_select_db('borcsa9_database') or die (2);

//Check if message is empty and send the error code

if(strlen($message) < 1){

   echo 3;

}

//Check if message is too long

else if(strlen($message) > 255){

   echo 4;

}

//Check if name is empty

else if(strlen($name) < 1){

   echo 5;

}

//Check if name is too long

else if(strlen($name) > 29){

   echo 6;

}

//Check if the name is used by somebody else

else if(mysql_num_rows(mysql_query("select * from chat where name = '" . $name . "' and ip != '" . @$REMOTE_ADDR . "'")) != 0){

   echo 7;

}

//If everything is fine

else{

   //This array contains the characters what will be removed from the message and name, because else somebody could send redirection script or links

   $search = array("<",">",">","<");

   //Insert a new row in the chat table

   mysql_query("insert into chat values ('" . time() . "', '" . str_replace($search,"",$name) . "', '" . @$REMOTE_ADDR . "', '" . str_replace($search,"",$message) . "')") or die(8);

}

?>

show-messages.php
<?php

//Connect to MySQL

mysql_connect('host','database','password');

//Select database

mysql_select_db('database') or die(2);

//Get the first 10 messages ordered by time

$result = mysql_query("select * from chat order by time desc limit 0,10");

$messages = array();

//Loop and get in an array all the rows until there are not more to get

while($row = mysql_fetch_array($result)){

   //Put the messages in divs and then in an array

   $messages[] = "<div class='message'><div class='messagehead'>" . $row[name] . " - " . date('g:i A M, d Y',$row[time]) . "</div><div class='messagecontent'>" . $row[message] . "</div></div>";

   //The last posts date

   $old = $row[time];

}

//Display the messages in an ascending order, so the newest message will be at the bottom

for($i=9;$i>=0;$i--){

   echo $messages[$i];

}

//This is the more important line, this deletes each message older then the 10th message ordered by time, so the table will never have to store more than 10 messages.

mysql_query("delete from chat where time < " . $old);

?>

This is a very simple chat system, I think the comments from the code are enough to understand it, but if not just ask me or check out a more detailed version of this tutorial: How to build a simple Chat system

#2
bbqroast

bbqroast

    Codecall Addict

  • Members
  • PipPipPipPipPipPipPip
  • 554 posts
Did you write ur self?
What is AJAX
Please, write clearly with proper structure. Double spacing makes the text feel un-jointed, Capitalizing Every Word Means People Stop Before Every Word Sub-Consciously Which Is A Pain In The Backside, and use code tags! (The right most styling box).

#3
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
@bbqroast:

The tutorial is on his site, so it seems so. AJAX is Asynchronous Javascript And XML, a method of calling a server side script on the same page without the need for refreshing (for the autoloading of new chat messages)


Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#4
Csabi

Csabi

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
Yes, I wrote it myself and yes ajax is Asynchronous Javascript And XML

#5
e11world

e11world

    Newbie

  • Members
  • Pip
  • 1 posts
Very useful code. Thank you very much!
Cheers,
Eddie Potros
http://www.e11world.com