PHP to implement simple chat room application code _php skills

Source: Internet
Author: User

Core Logic

Before defining the core functionality of your application, take a look at the basic look of the chat application, as shown in the screenshot below:

Enter the chat text through the input box at the bottom of the chat window. Click the Send button to start the function set_chat_msg. This is an AJAX based function, so you can send chat text to the server without refreshing the page. The program executes chat_send_ajax.php and user name and chat text in the server.

"////Set Chat message/function set_chat_msg () {if (typeof XMLHttpRequest!= 
  "undefined") {oxmlhttpsend = new XMLHttpRequest (); else if (window. 
  ActiveXObject) {oxmlhttpsend = new ActiveXObject ("Microsoft.XMLHTTP"); 
    } if (oxmlhttpsend = = null) {alert ("Browser does not support XML Http Request"); 
  Return 
  The var url = "chat_send_ajax.php"; 
  var strname= "Noname"; 
  var strmsg= ""; 
    if (document.getElementById ("txtname")!= null) {strname = document.getElementById ("Txtname"). Value; 
  document.getElementById ("Txtname"). Readonly=true; 
    } if (document.getElementById ("txtmsg")!= null) {strmsg = document.getElementById ("txtmsg"). Value; 
  document.getElementById ("Txtmsg"). Value = ""; 
  The URL = "? name=" + strname + "&msg=" + strmsg; 
  Oxmlhttpsend.open ("Get", url,true); 
Oxmlhttpsend.send (NULL); } 

The PHP module receives form data from the query string, which is updated to the database table named Chat. The Chat database table has columns named IDs, USERNAME, Chatdate, and MSG. The ID field is an automatically incremented field, so the assignment of this ID field is incremented automatically. The current date and time are updated to the Chatdate column.

Require_once (' dbconnect.php '); 
 
Db_connect (); 
 
$msg = $_get["msg"]; 
$DT = Date ("y-m-d h:i:s"); 
$user = $_get["name"]; 
 
$sql = "INSERT into chat (username,chatdate,msg)". 
   " VALUES (". QUOTE ($user). "," . 
   QUOTE ($DT). "," . QUOTE ($MSG). ");"; 
 
   echo $sql; 
 
$result = mysql_query ($sql); 
if (! $result) 
{ 
  throw new Exception (' Query failed: '. mysql_error ()); 
  Exit (); 
} 

To receive chat messages from all users in the database table, the timer function is set to loop 5 seconds to invoke the following JavaScript command, which is to perform the get_chat_msg function every 5 seconds.

var t = setinterval (function () {get_chat_msg ()},5000);

Get_chat_msg is an AJAX-based function. It executes the chat_recv_ajax.php program to obtain chat information from the database table. In the onReadyStateChange property, another JavaScript function get_chat_msg_result is connected. Program control enters the Get_chat_msg_result function while returning the chat message from the database table.

 
//General Ajax call 
// 
 
var oxmlhttp; 
var oxmlhttpsend; 
 
function get_chat_msg () 
{ 
  if (typeof XMLHttpRequest!= "undefined") 
  { 
    oxmlhttp = new XMLHttpRequest (); 
  } 
  else if (window. ActiveXObject) 
  { 
    oxmlhttp = new ActiveXObject ("Microsoft.XMLHTTP"); 
  } 
  if (oxmlhttp = = null) 
  { 
    alert ("Browser does not support XML Http Request"); 
    return; 
  } 
 
  Oxmlhttp.onreadystatechange = Get_chat_msg_result; 
  Oxmlhttp.open ("Get", "chat_recv_ajax.php", true); 
  Oxmlhttp.send (null); 
} 

In the chat_recv_ajax.php program, chat messages from users are collected through the SQL SELECT command. To limit the number of rows, a restriction clause (limit 200) is also given in the SQL query, which requires the last 200 rows in the Chat database table. The received message is then returned to the AJAX function to display the content in the Chat window.

Require_once (' dbconnect.php '); 
 
Db_connect (); 
$sql = "SELECT *, Date_format (chatdate, '%d-%m-%y%r ') as CDT from chat ORDER by ID desc limit 200"; $sql = "SELECT * from". $sql. 
") as Ch order by ID"; 
 
$result = mysql_query ($sql) or Die (' Query failed: '. mysql_error ()); 
Update Row Information $msg = ""; while ($line = Mysql_fetch_array ($result, Mysql_assoc)) {$msg = $msg. 
    "" . 
    "" . 
""; } $msg = $msg. "<table style=" color:blue; Font-family:verdana, Arial; 
 " . "font-size:10pt" border= "0" > <tbody><tr><td> ". 
 $line [CDT]. "</td><td>". 
 $line ["username"]. ": </td><td>". 
 $line ["MSG"]. 
 
"</td></tr></tbody></table>"; 
 
Echo $msg; As the data is ready, the JavaScript function collects the data from the PHP received. The data will be placed inside the div tag. 
 
Oxmlhttp.responsetext will retain the chat message received from the PHP program and copy it to the document.getElementById ("Div_chat") of the DIV tag. innerHTML properties. function Get_chat_msg_result (t) {if oxmlhttp.readystate==4 | | oxmlhttp.readystate== "complete") {if (document.getElementById ("div_chat")!= null) {document.getElementById ("Div_chat") 
      ). InnerHTML = Oxmlhttp.responsetext; 
    Oxmlhttp = null; 
    var scrolldiv = document.getElementById ("Div_chat"); 
  Scrolldiv.scrolltop = Scrolldiv.scrollheight;  } 
}

The following SQL CREATE TABLE command can be used to create a database table named Chat. All information entered by the user is entered into the database table.

CREATE TABLE Chat (id bigint auto_increment,username varchar (20),
chatdate datetime,msg varchar (), primary key (ID));

This code for implementing the chat application is very interesting, it can improve to become a fully fledged HTTP chat application, the logic of the creation of the application is very simple, even beginners understand that there will be no difficulty, I hope this article for the study of the help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.