How to implement PHP chat room application

Source: Internet
Author: User

Introduced

Chat apps are very common on the web. Developers have a lot to choose from when building such applications. This article describes how to implement a Php-ajax-based chat application, and you can send and receive messages without having to refresh the page.

Core Logic

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

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

////Set Chat message//function set_chat_msg () {if (typeof XMLHttpRequest! = "Unde    Fined ") {oxmlhttpsend = new XMLHttpRequest (); } else if (window.    ActiveXObject) {oxmlhttpsend = new ActiveXObject ("Microsoft.XMLHTTP");       } if (oxmlhttpsend = = null) {alert ("Browser does not support XML Http Request");    Return    } 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 = "";    } URL + = "? Name=" + strname + "&msg=" + strmsg;    Oxmlhttpsend.open ("GET", url,true); Oxmlhttpsend.send (null);} 

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

Require_once (' dbconnect.php ');d b_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 ();}

In order 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 execute 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 attribute, another JavaScript function get_chat_msg_result is connected. The program Controls access to 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 given in the SQL query, which requires the last 200 rows in the Chat database table. The obtained message is then returned to the AJAX function, which is used to display the content in the Chat window.

Require_once (' dbconnect.php ');d b_connect (); $sql = "SELECT *, Date_format (chatdate, '%d-%m-%y%r ') as CDT from chat order b Y ID desc LIMIT "; $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 received from PHP. The data will be placed within the DIV tag. Oxmlhttp.responsetext will keep the chat message received from the PHP program and copy it to the DIV tag's document.getElementById ("Div_chat"). innerHTML property.

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 will be entered into the database table.

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

Points of interest

This piece of code for implementing the chat application is very interesting. It can be improved to become a fully fledged HTTP chat application. The logic for creating the application is also very simple. Even beginners don't have any difficulty understanding them.

  • Related Article

    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.