Saturday 13 January 2018

Chat application using a database table in PHP - Part 2

This is the second update of Chat application using a database table in PHP.
This article is to describe a simple chat application in PHP or web chat application.

This article will be a solution to all your doubts like how to create a php chat room or php chat server, or php chat app or php chat box or php chat system. I wrote a php chat script in previous blog now improving that php chat example with prepared statements.

As you know using prepared statements it will become more secure. Because it can prevent SQL injection attacks.

You can download the complete zip file from this link:-
https://dl.dropboxusercontent.com/s/7td2j2jiahfpfw3/openchat_part2.zip
To know how to install and use watch this video.  (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)

Go to this link to subscribe to my YouTube channel to stay updated:- https://www.youtube.com/channel/UCxTp2yDew9m48Ch_hArOoYw

Here is the source code for chat application in php
 Here have two files index.php and back.php

 code
 index.php

<html>
    <head>
     
    </head>
    <body>
        <table width="100%" height="100%" border="1" align="center" valign="center">
            <tr><td colspan="2" height="6%"><h3>Chat Window</h3></td></tr>
            <tr><td colspan="2" height="6%"> From(Your Name or Id):&nbsp;&nbsp;<input type="text" name="sender" id="sender"><br></td></tr>
            <tr><td width='85%'>
                    <div id="chat_view" >
     
       &nbsp;
                    </div>
                </td>
                <td>
                    <div id="users" name="users">Online Users</div>
                </td>
            </tr>
        </table>
        <div id="chat_list"></div>
        <style type="text/css">
            .chat_box{
border-style:solid;
border-width:medium;
width:200px;
height:300px;
float:left;

}
#msg{
width:200px;
height:200px;
overflow:auto;
}
#new_msg_text
{
width:200px;
height:50px;
}
#close_button{
width:20px;
height:20px;
}
.user_list{

}
        </style>
     
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                window.setInterval(function() {
                   viewMsg();
                   viewOnlineUsers();
                   createNewChatBox();
                 
                },1000);
            });
         
            function creatNewBox(receiver)
            {
            var newbox ="<div class='chat_box' id='chat_box_"+receiver+"'>"+
            "<div id='chat_header'><input type='text' name='receiver[]' READONLY value='"+
            receiver+"' id='receiver'><span onclick='closeWindow($(this))'>X</span></div>"+
            "<div  height='20%' id='msg' >"+
                "<br><br><br></div>"+
             "<div id='newmsg'><textarea rows='4' cols='10' id='new_msg_text'>&nbsp;</textarea></div>"+
             "<input type='button' value='Send' id='btn' onclick='saveMsg($(this))'>"+
        "</div>";
     
        return newbox;
            }
         
            function createNewChatBox()
            {
             var sender=$("#sender").val();
    $("#chat_list").load('back.php?opt=get_chat&sender='+sender);
    $("input[name='chat_users[]']").each(function(){
 
viewBox($(this).val());
});
            }
            function viewBox(receiver)
            {
                if($.trim($("#sender").val())==$.trim(receiver))
                return;
               $(document).ready(function(){
               var flag=false;
              $("input[name='receiver[]']").each(function(){
           
if($(this).val()==receiver)
{flag=true;}
});
        if(flag==false)$("#chat_view").append(creatNewBox(receiver));         
               });
            }
         
            function viewOnlineUsers()
            {
                var sender=$("#sender").val();
                $("#users").load('back.php?opt=view_users&sender='+sender);
             
            }
            function closeWindow(obj)
            {
            obj.parent().parent().remove();
            }
         
            function viewMsg()
            {
                var sender=$("#sender").val();
$("input[name='receiver[]']").each(function(){
var receiver=$(this).val();
$("#chat_box_"+receiver).find("#msg").load('back.php?opt=view_msg&sender='+sender+"&receiver="+receiver);
});
}
       
        function saveMsg(obj)
        {
            var receiver=obj.parent().find("#receiver").val();
                         
            var sender=$("#sender").val();
            var msg=obj.parent().find("#new_msg_text").val();
         
           $.ajax({
           type: 'POST',
           url: 'back.php?opt=save',
           data: {"receiver":receiver,"sender":sender,"msg":msg},
           success: function(){
              obj.parent().find("#new_msg_text").val('');
           }
         
           });
        }
        </script>
     
    </body>
</html>

back.php
<?php
extract($_POST);
extract($_GET);
$con = new mysqli('localhost', 'root', 'password','chat_db');

switch ($opt)
{
    case "save":     
        $stmt = $con->prepare("INSERT INTO chat (sender,receiver,msg,time) values(?,?,?,NOW())");
        $stmt->bind_param("sss", $sender, $receiver, $msg);
        $stmt->execute();
    break;

    case "view_msg":       
        $stmt = $con->prepare("SELECT chat.*,users.user_id FROM chat  LEFT JOIN users ON users.user_id=chat.sender"
        ." WHERE (receiver= ? AND sender= ? )"
        ." OR (receiver= ? AND sender= ? ) ORDER BY time");
        $stmt->bind_param("ssss", $sender, $receiver, $receiver, $sender);
        $stmt->execute();
        $r = $stmt->get_result();
        while ($row = $r->fetch_assoc()) {
            echo "<table><tr>";
            echo "<td>".$row['user_id'].": ".$row['msg']."</td>";
            echo "</tr></table>";
        }
    break;
     
    case "get_chat":       
        $stmt = $con->prepare("SELECT DISTINCT  sender from chat ".
        "  WHERE receiver= ? AND AddTime(time, '00:00:15')>=NOW()");
        $stmt->bind_param("s", $sender);     
        $stmt->execute();
        $r = $stmt->get_result();
        while ($row = $r->fetch_assoc()) {     
        echo "<input type='text' name='chat_users[]' value='".$row['sender']."'>";
        }
    break;
 
    case "view_users":
            $stmt = $con->prepare("SELECT count(*) as count FROM users WHERE user_id= ?");
            $stmt->bind_param("s", $sender);     
            $stmt->execute();
            $r = $stmt->get_result();
            $row = $r->fetch_assoc();
            if($row['count']>0)
            {
                $stmt = $con->prepare("UPDATE users SET last_visit=NOW() WHERE user_id= ?");
                $stmt->bind_param("s", $sender);           
            }
            else
            {
            $stmt = $con->prepare("INSERT INTO users (user_id,last_visit) values(?,NOW())");
            $stmt->bind_param("s", $sender);
            }
           
            $stmt->execute();
            $stmt = $con->prepare("SELECT * FROM users WHERE AddTime(last_visit, '00:00:15')>=NOW()");
            $stmt->execute();
            $r = $stmt->get_result();
            while ($row = $r->fetch_assoc()) {
            echo "<table><tr>";     
            echo "<td><a onclick=\"viewBox('".$row['user_id']."')\">".$row['user_id']."</a></td>";
            echo "</tr></table>";
        }
    break;
}
?>


Here I am using two Mysql tables namely chat and users
chat

users

The query to make this tables
chat
CREATE TABLE IF NOT EXISTS `chat` (
  `sender` varchar(255) DEFAULT NULL,
  `receiver` varchar(255) DEFAULT NULL,
  `msg` text,
  `time` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

users
CREATE TABLE IF NOT EXISTS `users` (
  `user_id` varchar(255) NOT NULL,
  `last_visit` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

You can also read :- Chat application using a database table in PHP - Part 1
Chat application using a database table in PHP - Part 3

No comments:

Post a Comment

Search This Blog