Tuesday 24 July 2012

Chat application using a database table in PHP

This article is to describe a simple chat application in php or web chat application.
When think about how to create chat application in php  we can understand that. each user accessing
the webpage get a separate instance of the webpage and there have no direct
connection between two users using the same page at the same time.So we can use
a sql database to communicate with two users.

   Online chat application in php means a chat application using ajax or in othe words
 a jquery chat application.


You can download the complete zip file fromthis link:-
https://dl.dropboxusercontent.com/s/rv6aejvbqgphg61/openchat_part1.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'><img id='close_button' src='images/close_button.jpg' alt='X' onclick='closeWindow($(this))'/></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' 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(){
              
           alert("success");
           }
          
           });
        }
        </script>
       
    </body>
</html>


back.php
<?php



extract($_POST);
extract($_GET);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('sukesh');
switch ($opt) {
    case "save":
        $query = "INSERT INTO chat (sender,receiver,msg,time) values('" . $sender . "','" . $receiver . "','" . $msg . "',NOW()" . ")";
        mysql_query($query, $con) or die("Error...");

        break;

    case "view_msg":
       
        $query = "SELECT * FROM chat WHERE receiver='" . $sender. "' AND sender='".$receiver."'";
       
        $r = mysql_query($query, $con) or die("Error...");
        while ($row = mysql_fetch_array($r)) {
            echo "<table><tr>";
            echo "<td>".$row['msg']."</td>";

            echo "</tr></table>";
        }
        break;
       
        case "get_chat":
        $query = "SELECT DISTINCT  sender from chat ".
        "  WHERE receiver='$sender' AND AddTime(time, '00:00:15')>=NOW()";
        echo $query ;
           $r = mysql_query($query, $con) or die("Error...3");
        while ($row = mysql_fetch_array($r)) {
       
        echo "<input type='text' name='chat_users[]' value='".$row['sender']."'>";
        }
        break;
        case "view_users":
            $query = "SELECT count(*) as count FROM users WHERE user_id='".$sender."'";
            $r=mysql_query($query, $con) or die("Error...1");
            $row = mysql_fetch_array($r);
            if($row['count']>0)
                $query = "UPDATE users SET last_visit=NOW() WHERE user_id='".$sender."'";
                else
            $query = "INSERT INTO users (user_id,last_visit) values('".$sender."',NOW())";
             
            mysql_query($query, $con) or die("Error...2");
       
            $query = "SELECT * FROM users WHERE AddTime(last_visit, '00:00:15')>=NOW()";
           
     
        $r = mysql_query($query, $con) or die("Error...3");
        while ($row = mysql_fetch_array($r)) {
            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 2

Search This Blog