facebook like chat system using Ajax, mysql and php

122
1072

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";
        }
    }
?>

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

  10. Definitive journal of drugs and therapeutics. Definitive journal of drugs and therapeutics.
    [url=https://levaquin.science/#]can you get cheap levaquin without a prescription[/url]
    Read here. Everything about medicine.

  11. Actual trends of drug. safe and effective drugs are available.
    [url=https://lisinopril.science/#]buy lisinopril 20 mg without a prescription[/url]
    Drugs information sheet. Comprehensive side effect and adverse reaction information.

  12. Drugs information sheet. Comprehensive side effect and adverse reaction information.
    [url=https://mobic.store/#]get cheap mobic prices[/url]
    earch our drug database. Comprehensive side effect and adverse reaction information.

  13. earch our drug database. Actual trends of drug.
    [url=https://levaquin.science/#]can i purchase generic levaquin[/url]
    Commonly Used Drugs Charts. drug information and news for professionals and consumers.

  14. Definitive journal of drugs and therapeutics. Drugs information sheet.
    [url=https://azithromycins.online/]zithromax 500[/url]
    Read information now. Read information now.

  15. Drug information. Top 100 Searched Drugs. [url=https://amoxicillins.com/]amoxicillin price canada[/url]
    Comprehensive side effect and adverse reaction information. Prescription Drug Information, Interactions & Side.

  16. Best and news about drug. Get information now.
    [url=https://finasteridest.online]where buy generic propecia without rx[/url]
    Read now. Top 100 Searched Drugs.

  17. drug information and news for professionals and consumers. Top 100 Searched Drugs. [url=https://amoxicillins.online/]amoxicillin buy no prescription[/url]
    Get warning information here. Comprehensive side effect and adverse reaction information.

  18. Get information now. Read now.
    [url=https://azithromycins.com/]zithromax 500mg[/url]
    Some are medicines that help people when doctors prescribe. Read information now.

  19. Prescription Drug Information, Interactions & Side. earch our drug database.
    [url=https://edonlinefast.com]best erectile dysfunction pills[/url]
    Some are medicines that help people when doctors prescribe. Generic Name.

  20. Drugs information sheet. What side effects can this medication cause?
    [url=https://edonlinefast.com]ed drugs[/url]
    What side effects can this medication cause? Long-Term Effects.

  21. Everything about medicine. Drug information.
    [url=https://edonlinefast.com]best ed pills at gnc[/url]
    drug information and news for professionals and consumers. Cautions.

  22. Best and news about drug. Long-Term Effects.
    [url=https://canadianfast.online/#]prescription drugs without prior prescription[/url]
    Read information now. Long-Term Effects.

  23. Everything about medicine. Everything what you want to know about pills.
    [url=https://canadianfast.com/#]cvs prescription prices without insurance[/url]
    Read here. Some are medicines that help people when doctors prescribe.

  24. Read information now. Medscape Drugs & Diseases.
    [url=https://canadianfast.online/#]ed meds online without doctor prescription[/url]
    earch our drug database. earch our drug database.

  25. Reading your article helped me a lot and I agree with you. But I still have some doubts, can you clarify for me? I’ll keep an eye out for your answers.

  26. Get information now. Get here.
    [url=https://viagrapillsild.com/#]vegas viagra local[/url]
    Everything about medicine. All trends of medicament.

  27. Long-Term Effects. Get here.
    [url=https://viagrapillsild.online/#]sildenafil citrate[/url]
    Actual trends of drug. Long-Term Effects.

  28. Everything about medicine. Prescription Drug Information, Interactions & Side.
    [url=https://tadalafil1st.online/#]viagraorcialis[/url]
    Long-Term Effects. Get here.

  29. Read information now. Everything about medicine.
    [url=https://tadalafil1st.com/#]buy generic tadalafil online[/url]
    Read information now. drug information and news for professionals and consumers.

  30. What side effects can this medication cause? Actual trends of drug.
    [url=https://tadalafil1st.com/#]canada cialis with dapoxetine[/url]
    Medscape Drugs & Diseases. Prescription Drug Information, Interactions & Side.

  31. All trends of medicament. Cautions.
    https://amoxila.store/ can you buy amoxicillin over the counter

    [url=https://clomidc.fun/]where to buy generic clomid without rx[/url]

    [url=https://propeciaf.store/]order propecia[/url]
    Read here. п»їMedicament prescribing information.

  32. Cautions. Commonly Used Drugs Charts.
    [url=https://amoxila.store/]amoxicillin online no prescription[/url]
    Get information now. Top 100 Searched Drugs.

  33. Read now. safe and effective drugs are available.
    [url=https://amoxila.store/]amoxicillin 500mg cost[/url]

    can i buy propecia pills
    Learn about the side effects, dosages, and interactions. Comprehensive side effect and adverse reaction information.

  34. Some trends of drugs. Get information now.
    https://amoxila.store/ amoxicillin without a doctors prescription

    [url=https://zithromaxa.fun/]zithromax over the counter uk[/url]

    [url=https://clomidc.fun/]can i buy cheap clomid without dr prescription[/url]
    Everything information about medication. Some are medicines that help people when doctors prescribe.

  35. Read information now. Get here.

    [url=https://zithromaxa.fun/]order zithromax over the counter[/url]
    [url=https://amoxila.store/]amoxicillin 500 mg tablet[/url]

    [url=https://clomidc.fun/]how to buy cheap clomid prices[/url]
    Cautions. safe and effective drugs are available.

  36. Best and news about drug. Best and news about drug.

    [url=https://propeciaf.store/]where can i get generic propecia without dr prescription[/url]
    https://amoxila.store/ amoxicillin 500mg price canada
    Commonly Used Drugs Charts. Read information now.

  37. Get warning information here. Learn about the side effects, dosages, and interactions.
    [url=https://amoxila.store/]amoxicillin buy online canada[/url]

    https://zithromaxa.fun/ how to buy zithromax online
    Definitive journal of drugs and therapeutics. Actual trends of drug.

  38. Long-Term Effects. Everything what you want to know about pills.

    [url=https://propeciaf.store/]can i buy propecia[/url]

    https://zithromaxa.fun/ zithromax cost australia
    Get warning information here. Top 100 Searched Drugs.

  39. As I am looking at your writing, slotsite I regret being unable to do outdoor activities due to Corona 19, and I miss my old daily life. If you also miss the daily life of those days, would you please visit my site once? My site is a site where I post about photos and daily life when I was free.

  40. I’ve been looking for photos and articles on this topic over the past few days due to a school assignment, casinocommunity and I’m really happy to find a post with the material I was looking for! I bookmark and will come often! Thanks 😀

  41. Cool. I spent a long time looking for relevant content and found that your article gave me new ideas, which is very helpful for my research. I think my thesis can be completed more smoothly. Thank you.

  42. My brother recommended I might like this web site. He was totally right. This post actually made my day. You can not imagine just how much time I had spent for this info! Thanks!

LEAVE A REPLY

Please enter your comment!
Please enter your name here