Simple Chat using PHP, MySQLi, AJAX and JQuery

In this tutorial, I'm going to show you how to create a simple chat using PHP, MySQLi, AJAX and JQuery. I have created a sample chat room and sample users to focus this tutorial on creating a simple chat. Also, I have created a simple login, but if you want, you may learn How to Create a Login with Validation.

Creating our Database

First, we're going to create our database to hold our sample data and our chats. 1. Open phpMyAdmin. 2. Click databases, create a database and name it as "chat". 3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.
  1. CREATE TABLE `chat` (
  2.   `chatid` INT(11) NOT NULL AUTO_INCREMENT,
  3.   `chat_room_id` INT(11) NOT NULL,
  4.   `chat_msg` VARCHAR(100) NOT NULL,
  5.   `userid` INT(11) NOT NULL,
  6.   `chat_date` datetime NOT NULL,
  7. PRIMARY KEY(`chatid`)
  8. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  1. CREATE TABLE `chat_room` (
  2.   `chat_room_id` INT(11) NOT NULL AUTO_INCREMENT,
  3.   `chat_room_name` VARCHAR(50) NOT NULL,
  4. PRIMARY KEY(`chat_room_id`)
  5. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  1. CREATE TABLE `user` (
  2.   `userid` INT(11) NOT NULL AUTO_INCREMENT,
  3.   `username` VARCHAR(30) NOT NULL,
  4.   `password` VARCHAR(30) NOT NULL,
  5.   `your_name` VARCHAR(60) NOT NULL,
  6. PRIMARY KEY(`userid`)
  7. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
chat

Inserting Data into our Database

Next, we insert data into our database that will serve as our reference in this tutorial. 1. Click our database "chat". 2. Click SQL and paste the below codes.
  1. INSERT INTO `chat_room` (`chat_room_name`) VALUES
  2. ('Sample Chat Room');
  1. INSERT INTO `user` (`username`, `password`, `your_name`) VALUES
  2. ('neovic', 'devierte', 'neovic'),
  3. ('lee', 'ann', 'lee');

Creating our Connection

Next step is to create a database connection and save it as "conn.php". This file will serve as our bridge between our form and our database. To create the file, open your HTML code editor and paste the code below after the tag.
  1. <?php
  2. $conn = mysqli_connect("localhost","root","","chat");
  3.  
  4. // Check connection
  5.   {
  6.   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  7.   }
  8. ?>

Creating our Login Page

Next, we create a login page to determine our user that is needed when chatting. We name this as "index.php".
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Simple Chat using PHP/MySQLi, Ajax/JQuery</title>
  5. </head>
  6. <body>
  7. <h2>Login Here</h2>
  8. <form method="POST" action="login.php">
  9.  Username: <input type="text" name="username">
  10.  Password: <input type="password" name="password"> <br><br>
  11.  <input type="submit" value="Login">
  12. </form><br>
  13. <?php
  14.         session_start();
  15.         if (isset($_SESSION['message'])){
  16.         echo $_SESSION['message'];
  17.         unset ($_SESSION['message']);
  18.         }
  19. ?>
  20. </body>
  21. </html>

Creating our Login Code

Next, we create the code for our login. We name this as "login.php".
  1. <?php
  2.         session_start();
  3.         include('conn.php');
  4.        
  5.         $username=$_POST['username'];
  6.         $password=$_POST['password'];
  7.        
  8.         $query=mysqli_query($conn,"select * from `user` where username='$username' and password='$password'");
  9.        
  10.         if (mysqli_num_rows($query)<1){
  11.                 $_SESSION['message']="Login Error. Please Try Again";
  12.                 header('location:index.php');
  13.         }
  14.         else{
  15.                 $row=mysqli_fetch_array($query);
  16.                 $_SESSION['userid']=$row['userid'];
  17.                 header('location:home.php');
  18.         }
  19.  
  20. ?>

Creating our Homepage

This page will serve as a goto page after successful login. This is the page that the user can chat in the sample chat room. We name this as "home.php". This page also has our jquery script for chatting.
  1. <?php
  2.         include('conn.php');
  3.         session_start();
  4.         if (!isset($_SESSION['userid']) ||(trim ($_SESSION['userid']) == '')) {
  5.         header('location:index.php');
  6.     exit();
  7.         }
  8.        
  9.         $uquery=mysqli_query($conn,"select * from `user` where userid='".$_SESSION['userid']."'");
  10.         $urow=mysqli_fetch_assoc($uquery);
  11. ?>
  12. <!DOCTYPE html>
  13. <html>
  14. <head>
  15. <title>Simple Chat using PHP/MySQLi, Ajax/JQuery</title>
  16. </head>
  17. <body>
  18. <div>
  19.         <h4>Welcome, <?php echo $urow['your_name']; ?> <a href="logout.php">Logout</a></h4>
  20.         <?php
  21.                 $query=mysqli_query($conn,"select * from `chat_room`");
  22.                 while($row=mysqli_fetch_array($query)){
  23.                         ?>
  24.                                 <div>
  25.                                 Chat Room Name: <?php echo $row['chat_room_name']; ?><br><br>
  26.                                 </div>
  27.                                 <div id="result" style="overflow-y:scroll; height:300px;"></div>
  28.                                 <form>
  29.                                         <input type="text" id="msg">
  30.                                         <input type="hidden" value="<?php echo $row['chat_room_id']; ?>" id="id">
  31.                                         <button type="button" id="send_msg">Send</button>
  32.                                 </form>
  33.                         <?php
  34.                 }
  35.         ?>
  36. </div>
  37.  
  38. <script src = "jquery-3.1.1.js"></script>      
  39. <script type = "text/javascript">
  40.  
  41.         $(document).ready(function(){
  42.         displayResult();
  43.         /* Send Message */     
  44.                
  45.                 $('#send_msg').on('click', function(){
  46.                         if($('#msg').val() == ""){
  47.                                 alert('Please write message first');
  48.                         }else{
  49.                                 $msg = $('#msg').val();
  50.                                 $id = $('#id').val();
  51.                                 $.ajax({
  52.                                         type: "POST",
  53.                                         url: "send_message.php",
  54.                                         data: {
  55.                                                 msg: $msg,
  56.                                                 id: $id,
  57.                                         },
  58.                                         success: function(){
  59.                                                 displayResult();
  60.                                         }
  61.                                 });
  62.                         }      
  63.                 });
  64.         /*****  *****/
  65.         });
  66.        
  67.         function displayResult(){
  68.                 $id = $('#id').val();
  69.                 $.ajax({
  70.                         url: 'send_message.php',
  71.                         type: 'POST',
  72.                         async: false,
  73.                         data:{
  74.                                 id: $id,
  75.                                 res: 1,
  76.                         },
  77.                         success: function(response){
  78.                                 $('#result').html(response);
  79.                         }
  80.                 });
  81.         }
  82.        
  83. </script>
  84. </body>
  85. </html>

Creating our Send Message Code

Next step is to create our code for sending our chat message. We name this code as "send_message.php".
  1. <?php
  2.         include ('conn.php');
  3.         session_start();
  4.         if(isset($_POST['msg'])){              
  5.                 $msg = addslashes($_POST['msg']);
  6.                 $id = $_POST['id'];
  7.                 mysqli_query($conn,"insert into `chat` (chat_room_id, chat_msg, userid, chat_date) values ('$id', '$msg' , '".$_SESSION['userid']."', NOW())") or die(mysqli_error());
  8.         }
  9. ?>
  10. <?php
  11.         if(isset($_POST['res'])){
  12.                 $id = $_POST['id'];
  13.         ?>
  14.         <?php
  15.                 $query=mysqli_query($conn,"select * from `chat` left join `user` on user.userid=chat.userid where chat_room_id='$id' order by chat_date asc") or die(mysqli_error());
  16.                 while($row=mysqli_fetch_array($query)){
  17.         ?>     
  18.                 <div>
  19.                         <?php echo date('h:i A',strtotime($row['chat_date'])); ?><br>
  20.                         <?php echo $row['your_name']; ?>: <?php echo $row['chat_msg']; ?><br>
  21.                 </div>
  22.                 <br>
  23.         <?php
  24.                 }
  25.         }      
  26. ?>

Creating our Logout

Lastly, we create our logout code.
  1. <?php
  2.         session_start();
  3.  
  4.         session_destroy();
  5.         header('location:index.php');
  6.  
  7. ?>

Comments

how are you ?

Add new comment