PHP Chat System 2022 Tutorial on How to Create an AJAX and PHP Chat Application – Make a Live Chat Room or a One to One Chat Box in PHP Source Code using MySQL and jQuery – AJAX driven simple chat package blog

0
52
PHP Chat System


The Live Chat Code in PHP with Demo Helpers


The first helper script is refresh.php. It receives the last chat line ID from AJAX and pass it to a static class method that returns a JSON encoded response. Then the script outputs that as response to the AJAX requests. The code below is refresh.php code:


<?php
  require_once( "config.php" );
  require_once( "/path/to/class/chatClass.php" );
  $id = intval( $_GET[ 'lastTimeID' ] );
  $jsonData = chatClass::getRestChatLines( $id );
  print $jsonData;
?>


Second helper script is submit.php. It receives the chat text from AJAX and passes to static class method along with the user name and color from the session. We use start_session again to be able to access session data. The new data is inserted in the database. Below follows submit.php code:


<?php
  session_start();
  require_once( "config.php" );
  require_once( "/path/to/class/chatClass.php" );
  $chattext = htmlspecialchars( $_GET['chattext'] );
  chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>


Another file we need to create is config.php. it is a simple configuration file we are including in these two files where we define the database access variables.


<?php
  define("mysqlServer","localhost");
  define("mysqlDB","mysqlDB");
  define("mysqlUser","mysqlUser");
  define("mysqlPass","mysqlPass");
?>

The Main AJAX Chat PHP Class


The last file left to explain is the class itself. Let us copy this code in chatClass.php file:


<?php

  class chatClass
  {
    public static function getRestChatLines($id)
    {
      $arr = array();
      $jsonData="{"results":[";
      $db_connection = new mysqli( mysqlServer, mysqlUser, mysqlPass, mysqlDB);
      $db_connection->query( "SET NAMES 'UTF8'" );
      $statement = $db_connection->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
      $statement->bind_param( 'i', $id);
      $statement->execute();
      $statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
      $line = new stdClass;
      while ($statement->fetch()) {
        $line->id = $id;
        $line->usrname = $usrname;
        $line->color = $color;
        $line->chattext = $chattext;
        $line->chattime = date('H:i:s', strtotime($chattime));
        $arr[] = json_encode($line);
      }
      $statement->close();
      $db_connection->close();
      $jsonData .= implode(",", $arr);
      $jsonData .= ']}';
      return $jsonData;
    }
    
    public static function setChatLines( $chattext, $usrname, $color) {
      $db_connection = new mysqli( mysqlServer, mysqlUser, mysqlPass, mysqlDB);
      $db_connection->query( "SET NAMES 'UTF8'" );
      $statement = $db_connection->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
      $statement->bind_param( 'sss', $usrname, $color, $chattext);
      $statement->execute();
      $statement->close();
      $db_connection->close();
    }
  }
?>


To connect to the database we need login information, so use constant values defined separately with MySQL connection values like the server name, database name, MySQL username and password.


In this class we have only two methods: one to retrieve chat lines from the database named getRestChatLines(). The other is to insert new chat lines to the database named as setChatLines().


The getRestChatLines() method receives one data element, the last chat line ID. It connects to MySQL database through the improved extension MySQLi and queries the database for the newest chat lines.

The queried chat lines must all be newer than our last chat line, and must not be older than one hour. We are limiting it to one hour to avoid causing excessive load to the server. The results are sorted in an array, and returned back as a JSON encoded data. Notice that the timestamp is converted to a readable time format.


The setChatLines() method receives three data elements:  the chat text, who sent the text and its color. It connects to the MySQL database and inserts the new chat line with an INSERT statement. This method will not return anything.

As a final note, I just would like to remind that database access operations may fail eventually due to unexpected errors. The code shown above does not contain all the error checks that it should tp be robust. Error checking was omitted to avoid making the code look more complicated just for this tutorial.

Keep that in mind when implementing any kind of database access applications, so your code can be as robust as code written by a good professional developer.



Source link

Leave a reply

Please enter your comment!
Please enter your name here