Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Simple Chat system using PHP, MySQL and Ajax

innerHTML mysql ajax

  • Please log in to reply
8 replies to this topic

#1 Csabi

Csabi

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 60 posts

Posted 17 September 2010 - 05:12 AM

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
  • 1
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#2 bbqroast

bbqroast

    Codecall Addict

  • Senior Member
  • PipPipPipPipPipPip
  • 564 posts
  • Location:/etc/passwd

Posted 26 September 2010 - 06:32 PM

Did you write ur self?
What is AJAX
  • 0
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

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 26 September 2010 - 08:13 PM

@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)


  • 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.


#4 Csabi

Csabi

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 60 posts

Posted 27 September 2010 - 04:18 AM

Yes, I wrote it myself and yes ajax is Asynchronous Javascript And XML
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#5 e11world

e11world

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 27 September 2010 - 11:46 AM

Very useful code. Thank you very much!
  • 0

#6 Hamed

Hamed

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 413 posts

Posted 13 October 2012 - 05:56 PM

Can you make downloadable version?
  • 0

#7 VNFox

VNFox

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 648 posts
  • Programming Language:C#, PHP
  • Learning:Assembly

Posted 13 October 2012 - 08:48 PM

Can you attach the zip file ?
  • 1

www.pickmike.com
I don't just develop software. I find solutions to your business needs.


#8 DrDean

DrDean

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 18 June 2013 - 08:34 PM

Is there a way to sign out without refreshing the whole page? current code is: window.location.reload() Thanks...


Edited by DrDean, 18 June 2013 - 08:36 PM.

  • 0

#9 ali156354

ali156354

    CC Lurker

  • New Member
  • Pip
  • 5 posts

Posted 27 September 2014 - 08:27 AM

hi.i have problem here

case 6:
error = 'The name is too long!';
break


  • 0