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.

           Before go through the source code you can see a sample screen shot here
 Please open this same page in another tab or another browser to test the chat application.
For reduce  complexity I am not using a user login.You can simply login to chat by using your name or nick
name without any log up process.


Enter your name like Xwe , Yrt , Zty  in the From text box.You can see the online users in the right column.Click one of the
names , you can see a chat box is opened.You can write messages in it and send to the selected user.


You can download the complete zip file fromthis link:-
http://sukeshbr.freeiz.com/blog_works/openchat/openchat.zip
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 :-
Simple Game Using Jquery

38 comments:

  1. ths coding is use but i need mulitple user chatting application in php like LinkedIn sir..

    ReplyDelete
    Replies
    1. Did you mean a group chat?
      For what you want this chat application?If you are trying to make a social networking site,then download dolphin framework and make changes to it as your like.

      If you trying to make this application to group chat,it will be easy.

      Delete
  2. not working fine its showing only display no chatting is posoble... tell me how to do it plzzz.....

    ReplyDelete
  3. hi friend,

    1.First in the 'From(Your Name or Id):' text field enter your name

    2.In the right panel with heading 'Online Users' you can see the online peoples who are available to chat. Unfortunately you can't see anyone in that list,because
    there hasn't any chance for another person using this chat at
    the time when you are using it because of the limited pageview of my blog.So you must open the same URL in another tab, then you can see your name
    in the previous tab is listed in the online user list.

    3.Type another name in this new tab
    4. click your name from the online users list.You can see a small chat window is populated.In this window you can type
    the message and send it by click in the send button

    Thank you

    ReplyDelete
    Replies
    1. hello, in this chat application not viewing the receiver command from receiver and also sender command from sender how to create this

      Delete
  4. Hi Karthikeyan,

    It is a limitation of my chat application.I will fix it in the next update.
    Edit back.php like this

    in the case "view_msg": edit the query like this

    $query = "SELECT * FROM chat WHERE (receiver='" . $sender. "' AND sender='".$receiver."') OR (receiver='".$receiver."' and sender='". $sender."') order by time ";



    I am sorry about this,because it is not a tested code segment.But I believe that it will works for you.

    ReplyDelete
    Replies
    1. SELECT DISTINCT sender from chat WHERE receiver='' AND AddTime(time, '00:00:15')>=NOW()Error...3

      Delete
  5. hey.. thanx for the code... i need a help. what if i want to display the name of the message sender.... i know its a bit silly but i am very new to php so can u plz tell me how.

    ReplyDelete
    Replies
    1. Hi Kodali,
      Now the current code is displaying the sender name in a text box at the top of the chat box.

      Delete
  6. ya its displaying but i want the name of the mesage writer against each msg too...
    like if a and b are conversing..
    a's chat box
    a:hii
    b:how r u??
    a:i am fyn.. hw r u??
    b's chatbox
    a:hii
    b:how r u??
    a:i am fyn.. hw r u??
    Thanx in advance

    ReplyDelete
    Replies
    1. plz put it on view msg td $row['sender']."::".$row['msg']

      Delete
  7. dude if i want to include smilet feature .. like if i enter something as :) it should display appropriate smiley image

    ReplyDelete
  8. Anonymous ,

    You are correct.Thanks for your effort.For a few a days I was busy.So I can't reply to brayan and Kodali Deepika.

    I will give you a reply as soon as possible.

    ReplyDelete
  9. hai sukesh thanks for your support ..actualy i am stuck on msg sending..how can i send a mesage on presing enter key make it fazt..itz very urgent..

    ReplyDelete
  10. Anonymous,

    add this code in the function
    creatNewBox(receiver) and try again.It may work



    $("#new_msg_text").keypress(function (e) {
    e.preventDefault();
    var key = window.event ? e.keyCode : e.which;
    if (key == '13') {
    saveMsg($(this));
    }
    });

    ReplyDelete
    Replies
    1. 1.how can i minimize a winodow when new window open
      2.display invisible users(not in online)

      Delete
    2. i hope that you will finish it on tomorrow

      Delete
  11. Minimise the window will be a big task,and it requires more time to complete.I will implement it in the next update.
    Their is no login is implemented now.So we can't identify the invisible users

    ReplyDelete
    Replies
    1. chat not working in IE ....

      Delete
  12. Great Work ..This is wonderful......

    ReplyDelete
  13. gteat working

    ReplyDelete
  14. gud application
    it is useful
    i have one doubt
    i want to know the working procedure of this application by using andriod emulators

    ReplyDelete
  15. hi Venkatesh,
    try phonegap.
    http://docs.phonegap.com/

    ReplyDelete
    Replies
    1. thanks sukesh
      can u please provide supported java files for these application to deploy in a emulator

      Delete
  16. This comment has been removed by the author.

    ReplyDelete
  17. nice application thanx
    how to provide secure login in it and then start chatting?

    ReplyDelete
  18. How can i modify it admin-clients chat(one -many )?help me soon

    ReplyDelete
  19. without creating form in html is it possible

    ReplyDelete
  20. and how about xml response in AJAX

    ReplyDelete
  21. Online Group Chat Script with full Source code & demo
    http://grprajapat.blogspot.in/2014/09/chat-script-in-php-with-full-source.html

    ReplyDelete
  22. hai sukesh Chat application using a database table in PHP will not work different browser
    wil you send the script and guide of work in different browser such as chrome,internetexplorer

    ReplyDelete
  23. hai sukesh Chat application using a database table in PHP will not work different browser
    wil you send the script and guide of work in different browser such as chrome,internetexplorer

    ReplyDelete
  24. excellent application... working perfectly.. gppd luck brother..

    ReplyDelete
  25. I Would like to Share about GroupRocket.Net, I do work for GroupRocket, You May think, My Comment is bias but I do believe GroupRocket is helpful for communication at work or making chatting about work even better.

    ReplyDelete
  26. Excellent work..I would like to ad this chat box in my blog. Please guide me, how to ad this to a blogger post. All the steps required. Thank you

    ReplyDelete
  27. what is the complexity of you chat

    ReplyDelete
  28. what is the complexity of you chat

    ReplyDelete
  29. I like the valuable information on chat application you provide in your articles. I’ll bookmark your weblog and check again here often. Best of luck for the next! Thanks for such post and keep it up.

    ReplyDelete

Search This Blog