facebook like chat system using Ajax, mysql and php

37
590

Welcome back to shortlearner, today we will learn how to implement a chat system using PHP, AJAX,and MySQL.

before start the tutorial i would like to suggest you to have some basic knowledge of ajax and jquery.

in this tutorial we willl used bootstrap maxcdn class to improve the visual looks of our web page,

we use ajax functionality for quick response of our chat system,  and we will also used mysqli to prevent sql  injections and store the whole conversation in our database.

first of all we would discuss about our database schema.

in the chat system we will make a database with the name of fb_msg, in this database we will create three tables for storing messages and users information.

in the very first table (admin) we will create 4 entities inside it like id, email, password and pic. in the user table we made id field as a auto increment to prevent duplication of data.
in the second table (conversation) we will create 3 entities inside it like id , user_one, and  user_two. in the conversation table we made id field as a unique key for assigning each conversation a unique, non-repetitive conversation id for every user.

in the last table (message) we will create 5 entities inside it like id,conversation_id, user_from,user_to,message . in the message table we will store the id of conversation table , in conversation id, in user_from we will store the id of sender and in user_to we will fetch the id of the receiver.

After Making the database we will make a connection in php to connect with our database.. for makinng connection in php i prefer to make a separate file which contains the code of connecting the database.

config.php

<?php
$con = mysqli_connect("localhost","root","","fb_msg");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

After making connection we will moved into our front end part.

Index.php / Login Page

<?php session_start();
if(isset($_POST["LOGIN"]))
{
    $email=$_POST["email"];
    $password=$_POST["password"];
require("connection.php");
   echo   $qry="SELECT * FROM admin WHERE email='$email' AND password='$password';";
    $result = mysqli_query($con,$qry);
    $row = mysqli_fetch_array($result);
      $_SESSION["email"] = $email;
          $_SESSION['id'] = $row['id'];
        header("location:message.php");
  } 
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<link rel="stylesheet" href="adcss/style.css">
<script src="adjs/ad.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div>
<div style="margin-top:20px">
    <div>
        <form role="form" method="post" action="#" >
            <fieldset>
                <h2>Please Sign In</h2>
                <hr>
                <div>
                    <input type="email" name="email" id="email" placeholder="Email Address">
                </div>
                <div>
                    <input type="password" name="password" id="password" placeholder="Password">
                </div>
                <span>
                    <button type="button" data-color="info">Remember Me</button>
                    <input type="checkbox" name="remember_me" id="remember_me" checked="checked">
                    <a href="">Forgot Password?</a>
                </span>
                <hr>
                <div>
                    <div>
                        <input type="submit" value="Sign In" name="LOGIN">
                    </div>
                    <div>
                        <a href="">Register</a>
                    </div>
                </div>
            </fieldset>
        </form>
    </div>
</div>
</div>
</body>
</html>

after hit on login button a sessions is created with email,id,and if the user is authenticated then the session will redirect on message.php page otherwise the session will redirect on index.php again.

in message.php we will fetch all the registered user on the left corner of our chatroom, after click on a specific user a conversation is initiated between both users.

<?php
    //connect to the database
    require_once("connection.php");
    session_start();
    //shop not login  users from entering 
    if(isset($_SESSION['id'])){
        $user_id = $_SESSION['id'];
    }else{
        header("Location: index.php");
    }
?>
<!DOCTYPE html>
<html>
<head>
<style>
#navbar.affix {
    position: fixed;
    top: 0;
    width: 100%;
    z-index:10;
}
</style>
    <title>Main VPS Provider</title>
 <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="css/fb_style.css">
</head>
<body>
<div id="navbar">
    <nav>
        <div>
            <ul>
                <li>
                    <a href="#about">
                        About
                    </a>
                </li>
                <li>
                    <a href="#services">
                        Services
                    </a>
                </li>
                <li>
                    <a href="#products">
                        Products
                    </a>
                </li>
                <li>
                    <a href="#reviews">
                        Reviews
                    </a>
                </li>
                <li>
                    <a href="#contact">
                        Contact
                    </a>
                </li>
            </ul>
        </div>
    </nav>
</div>
<div>
<div>
    <center>
        <strong>Welcome <?php echo $_SESSION['email']; ?>  <a href="logout.php">logout</a></strong>
    </center>
    <div>
        <div>
            <ul>
                <?php
                    //show all the users expect me
                    $q = mysqli_query($con, "SELECT * FROM `admin` WHERE id!='$user_id'");
                    //display all the results
                    while($row = mysqli_fetch_assoc($q)){
                        echo "<a href='message.php?id={$row['id']}'><li><img src='{$row['pic']}'> {$row['email']}</li></a>";
                    }
                ?>
            </ul>
        </div>
        <div>
            <!-- display message -->
            <div>
            <?php
                //check $_GET&#91;'id'&#93; is set
                if(isset($_GET['id'])){
                    $user_two = trim(mysqli_real_escape_string($con, $_GET['id']));
                    //check $user_two is valid
                    $q = mysqli_query($con, "SELECT `id` FROM `admin` WHERE id='$user_two' AND id!='$user_id'");
                    //valid $user_two
                    if(mysqli_num_rows($q) == 1){
                        //check $user_id and $user_two has conversation or not if no start one
                        $conver = mysqli_query($con, "SELECT * FROM `conversation` WHERE (user_one='$user_id' AND user_two='$user_two') OR (user_one='$user_two' AND user_two='$user_id')");
                        //they have a conversation
                        if(mysqli_num_rows($conver) == 1){
                            //fetch the converstaion id
                            $fetch = mysqli_fetch_assoc($conver);
                            $conversation_id = $fetch['id'];
                        }else{ //they do not have a conversation
                            //start a new converstaion and fetch its id
                            $q = mysqli_query($con, "INSERT INTO `conversation` VALUES ('','$user_id',$user_two)");
                            $conversation_id = mysqli_insert_id($con);
                        }
                    }else{
                        die("Invalid $_GET ID.");
                    }
                }else {
                    die("Click On the Person to start Chating.");
                }
            ?>
            </div>
            <!-- /display message -->
            <!-- send message -->
            <div>
                <!-- store conversation_id, user_from, user_to so that we can send send this values to post_message_ajax.php -->
                <input type="hidden" id="conversation_id" value="<?php echo base64_encode($conversation_id); ?>">
                <input type="hidden" id="user_form" value="<?php echo base64_encode($user_id); ?>">
                <input type="hidden" id="user_to" value="<?php echo base64_encode($user_two); ?>">
                <div>
                    <textarea id="message" placeholder="Enter Your Message"></textarea>
                </div>
                <button id="reply">Reply</button> 
                <span id="error"></span>
            </div></div>
            <!-- / send message -->
    </div>
</div>
</div>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/script.js"></script> 
</body>
</html>

For quick response of conversations we will used ajax script to send or receive message swiftly.

inside the js folder we will created two java script files which contains the sending and receiving process of messages inside it.

in the below ajax code we will create a system to send and receive messages between users with the help of two

pages like post_message_ajax.php and get_message_ajax.php. in  send_message_ajax.php page the message will send to the receiver  and it will get stored in the message table of our database. in receive_message_ajax.php page the stored messages are fetched from the message table of our database and rapidly shown to the receiver with the help of ajax script.

$(document).ready(function(){
    /*post message via ajax*/
    $("#reply").on("click", function(){
        var message = $.trim($("#message").val()),
            conversation_id = $.trim($("#conversation_id").val()),
            user_form = $.trim($("#user_form").val()),
            user_to = $.trim($("#user_to").val()),
            error = $("#error");
        if((message != "") && (conversation_id != "") && (user_form != "") && (user_to != "")){
            error.text("Sending...");
            $.post("post_message_ajax.php",{message:message,conversation_id:conversation_id,user_form:user_form,user_to:user_to}, function(data){
                error.text(data);
                //clear the message box
                $("#message").val("");
            });
        }
    });
    //get message
    c_id = $("#conversation_id").val();
    //get new message every 2 second
    setInterval(function(){
        $(".display-message").load("get_message_ajax.php?c_id="+c_id);
    }, 2000);
    $(".display-message").scrollTop($(".display-message")[0].scrollHeight);
});

post_message_ajax.php

<?php
    require_once("connection.php");
    //post message
    if(isset($_POST['message'])){
        $message = mysqli_real_escape_string($con, $_POST['message']);
        $conversation_id = mysqli_real_escape_string($con, $_POST['conversation_id']);
        $user_form = mysqli_real_escape_string($con, $_POST['user_form']);
        $user_to = mysqli_real_escape_string($con, $_POST['user_to']);
        //decrypt the conversation_id,user_from,user_to
        $conversation_id = base64_decode($conversation_id);
        $user_form = base64_decode($user_form);
        $user_to = base64_decode($user_to);
        //insert into `messages`
        $q = mysqli_query($con, "INSERT INTO `messages` VALUES ('','$conversation_id','$user_form','$user_to','$message')");
        if($q){
            echo "Posted";
        }else{
            echo "Error";
        }
    }
?>

get_message_ajax.php

<?php
    require_once("connection.php");
    if(isset($_GET['c_id'])){
        //get the conversation id and
        $conversation_id = base64_decode($_GET['c_id']);
        //fetch all the messages of $user_id(loggedin user) and $user_two from their conversation
        $q = mysqli_query($con, "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'");
        //check their are any messages
        if(mysqli_num_rows($q) > 0){
            while ($m = mysqli_fetch_assoc($q)) {
                //format the message and display it to the user
                $user_form = $m['user_from'];
                $user_to = $m['user_to'];
                $message = $m['message'];
                //get name and image of $user_form from `user` table
                $user = mysqli_query($con, "SELECT email,pic FROM `admin` WHERE id='$user_form'");
                $user_fetch = mysqli_fetch_assoc($user);
                $user_form_username = $user_fetch['email'];
                $user_form_img = $user_fetch['pic'];
                //display the message
                echo "
                            <div class='message'>
                                <div class='img-con'>
                                    <img src='{$user_form_img}'>
                                </div>
                                <div class='text-con'>
                                    <a href='#''>{$user_form_username}</a>
                                    <p>{$message}</p>
                                </div>
                            </div>
                            <hr>";
            }
        }else{
            echo "No Messages";
        }
    }
?>

37 COMMENTS

  1. [url=https://over-the-counter-drug.com/#]over the counter ed pills[/url] over the counter anti inflammatory

  2. [url=https://over-the-counter-drug.com/#]п»їover the counter anxiety medication[/url] nystatin cream over the counter

  3. [url=https://over-the-counter-drug.com/#]over the counter uti medicine[/url] the best over counter sleep aid

  4. desyrel aleve back patch reviews In addition to Zetec, Zetec Titanium models get sat nav, 16 inch alloys and a redesigned centre console, while Titanium Navigator models add Sony sat nav and rear parking sensors Kjop lasix

  5. There is no doubt in my mind I allege he is one of the biggest race fixing jerks in the history of horse racing nolvadex d CrossrefMedlineGoogle Scholar 49 Hartmann F, Packer M, Coats AJ, Fowler MB, Krum H, Mohacsi P, Rouleau JL, Tendera M, Castaigne A, Trawinski J, Amann Zalan I, Hoersch S, Katus HA

  6. What side effects can this medication cause? earch our drug database.
    [url=https://stromectolst.com/#]ivermectin usa[/url]
    п»їMedicament prescribing information. Definitive journal of drugs and therapeutics.

  7. п»їMedicament prescribing information. Drugs information sheet.
    [url=https://stromectolst.com/#]ivermectin cream 1%[/url]
    Prescription Drug Information, Interactions & Side. Read information now.

  8. What side effects can this medication cause? Commonly Used Drugs Charts.
    [url=https://stromectolst.com/#]ivermectin syrup[/url]
    Read here. Actual trends of drug.

  9. Everything information about medication. drug information and news for professionals and consumers.
    [url=https://stromectolst.com/#]stromectol covid 19[/url]
    Medscape Drugs & Diseases. Drugs information sheet.

LEAVE A REPLY

Please enter your comment!
Please enter your name here