PHP implementation of the simplest chat room application _php Tutorial

Source: Internet
Author: User

PHP for the simplest chat room app


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.

 
 
  1. //
  2. //Set Chat Message
  3. //
  4. function set_chat_msg ()
  5. {
  6. if (typeof XMLHttpRequest! = "undefined")
  7. {
  8. Oxmlhttpsend = new XMLHttpRequest ();
  9. }
  10. Else if (window. ActiveXObject)
  11. {
  12. Oxmlhttpsend = new ActiveXObject ("Microsoft.XMLHTTP");
  13. }
  14. if (Oxmlhttpsend = = null)
  15. {
  16. Alert ("Browser does not support XML Http Request");
  17. return ;
  18. }
  19. var url = "chat_send_ajax.php";
  20. var strname="Noname";
  21. var strmsg="";
  22. if (document.getElementById ("txtname")! = null)
  23. {
  24. strname = document.getElementById ("txtname"). Value;
  25. document.getElementById ("txtname"). readonly=true;
  26. }
  27. if (document.getElementById ("txtmsg")! = null)
  28. {
  29. strmsg = document.getElementById ("txtmsg"). Value;
  30. document.getElementById ("txtmsg"). Value = "";
  31. }
  32. URL + = "? name=" + strname + "&msg=" + strmsg;
  33. Oxmlhttpsend.open ("GET", URL,true);
  34. Oxmlhttpsend.send (null);
  35. }

The PHP module receives the form data from query string queries and updates it to a database table named Chat. The Chat database table has ID columns named,, 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.

 
 
  1. require_once (' dbconnect.php ');
  2. Db_connect ();
  3. $msg = $_get["msg"];
  4. $dt = Date ("y-m-d h:i:s");
  5. $user = $_get["name"];
  6. $sql ="INSERT into chat (username,chatdate,msg)" .
  7. "VALUES (" . QUOTE ($user). "," .
  8. QUOTE ($DT). "," . QUOTE ($msg). ");" ;
  9. Echo $sql;
  10. $result = mysql_query ($sql);
  11. if (! $result)
  12. {
  13. Throw New Exception (' Query failed: ' . mysql_error ());
  14. Exit ();
  15. }

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.

 
 
  1. //
  2. //General Ajax Call
  3. //
  4. var oxmlhttp;
  5. var oxmlhttpsend;
  6. function get_chat_msg ()
  7. {
  8. if (typeof XMLHttpRequest! = "undefined")
  9. {
  10. Oxmlhttp = new XMLHttpRequest ();
  11. }
  12. Else if (window. ActiveXObject)
  13. {
  14. Oxmlhttp = new ActiveXObject ("Microsoft.XMLHTTP");
  15. }
  16. if (oxmlhttp = = null)
  17. {
  18. Alert ("Browser does not support XML Http Request");
  19. return ;
  20. }
  21. Oxmlhttp.onreadystatechange = Get_chat_msg_result;
  22. Oxmlhttp.open ("GET","chat_recv_ajax.php",true);
  23. Oxmlhttp.send (null);
  24. }

In the chat_recv_ajax.php program, chat messages from users are collected through SQL select commands. To limit the number of rows, the 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.

 
 
  1. require_once (' dbconnect.php ');
  2. Db_connect ();
  3. $sql = "SELECT *, Date_format (chatdate,'%d-%m-%y%r ')
  4. As CDT from the chat order by ID desc limit";
  5. $sql = "SELECT * FROM (" . $sql. ") as Ch ORDER by ID";
  6. $result = mysql_query ($sql) or Die (' query failed: ' . mysql_error ());
  7. //Update Row information
  8. $msg ="";
  9. while ($line = mysql_fetch_array ($result, MYSQL_ASSOC))
  10. {
  11. $msg = $msg. "" .
  12. "" .
  13. "" ;
  14. }
  15. $msg = $msg. "
  16. "FONT-SIZE:10PT;" border= "0" >
  17. < span=""> " . $line ["CDT"].
  18. "
  19. " . $line ["username"].
  20. ":
  21. " . $line ["MSG"].
  22. "
  23. ";
  24. Echo $msg;
  25. 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.
  26. function Get_chat_msg_result (t)
  27. {
  28. if (oxmlhttp.readystate==4 | | oxmlhttp.readystate=="complete")
  29. {
  30. if (document.getElementById ("Div_chat")! = null)
  31. {
  32. document.getElementById ("Div_chat"). InnerHTML = Oxmlhttp.responsetext;
  33. Oxmlhttp = null;
  34. }
  35. var scrolldiv = document.getElementById ("Div_chat");
  36. Scrolldiv.scrolltop = Scrolldiv.scrollheight;
  37. }
  38. }

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 (20),
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.

License

This article, as well as any related source code and files, has been licensed by the Code Project Open License (Cpol).

Link: http://www.codeceo.com/article/php-chart-app.html
English Original: Chat application in PHP

http://www.bkjia.com/PHPjc/1027371.html www.bkjia.com true http://www.bkjia.com/PHPjc/1027371.html techarticle PHP implements the simplest chat room app to introduce chat apps that are very common on the web. Developers have a lot to choose from when building such applications. This article describes how to implement ...

  • 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.