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. if (isset($_SESSION['message'])){
  15. echo $_SESSION['message'];
  16. unset ($_SESSION['message']);
  17. }
  18. ?>
  19. </body>
  20. </html>

Creating our Login Code

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

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

Creating our Logout

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

Comments

Submitted byPrathameshNimje (not verified)on Fri, 05/19/2023 - 19:57

how are you ?

Add new comment