Wednesday, 31 January 2018

Chat application using a database table in PHP - Part 3

This is the third update of Chat application using a database table in PHP.
This article is the continution of a simple chat application in PHP or web chat application using live chat rest api.

Previous articles were solution to 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. This time I have created rest api for chat.Rest apis using json so now I can call it a json chatbot, json chat server, json chat room or collectively json chat php script.

By using rest api we can separate back end and front end into separate sections. So implement this chat to other platforms like android will become easy.

You can download the complete zip file from this link:-
https://dl.dropboxusercontent.com/s/8jsal21eo73xrl6/openchat_part3.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)
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>Online Users</div>
<ul id="users">                   
</ul>
</td>
</tr>
</table>
<div id="chat_list"></div>
<style type="text/css">
.chat_box{
border-style:solid;
border-width:medium;
width:200px;
height:310px;
float:left;
margin-left:2px;

}
#msg{
width:200px;
height:200px;
overflow:auto;
}
#new_msg_text
{
width:200px;
height:50px;
resize: none;
}
#close_button{
width:20px;
height:20px;
padding-left:2px;
}
#users{
list-style: none;
padding:0px;
}
</style>

<script type="text/javascript" src="./jquery.1.11.1.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' style='width:180px;' 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>"+
"<div><input type='button' value='Send' id='btn' onclick='saveMsg($(this))'></div>"+
"</div>";

return newbox;
}

function createNewChatBox()
{
var sender=$("#sender").val();
$.ajax({
type: 'GET',
url: 'back.php?opt=get_chat&sender='+sender,
success: function(data){
if(data.status==true)
{
$('#chat_list').html('');
data.data.users.forEach(function(user,index){
if(user.sender!='')
{
$('#chat_list').append("<input type='text' name='chat_users[]' value='"
+user.sender+"'>");
viewBox(user.sender);
}   
});

}
}          
});

}

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();
$.ajax({
type: 'GET',
url: 'back.php?opt=view_users&sender='+sender,
success: function(data){
if(data.status==true)
{
$('#users').html('');
data.data.users.forEach(function(user,index){
if(user.user_id!='')
{
$('#users').append("<li><a onclick=\"viewBox('"+user.user_id+"')\">"
+user.user_id+"</a></li>");
}   
});

}
}

});

}
function closeWindow(obj)
{
obj.parent().parent().remove();
}

function viewMsg()
{
var sender=$("#sender").val();
$("input[name='receiver[]']").each(function(){
var receiver=$(this).val();
$.ajax({
type: 'GET',
url: 'back.php?opt=view_msg&sender='+sender+"&receiver="+receiver,
success: function(data){
if(data.status==true)
{
$("#chat_box_"+receiver).find("#msg").html('');
data.data.messages.forEach(function(message,index){
if(message.user_id!='' && message.msg!='')
{
$("#chat_box_"+receiver).find("#msg").append("<table<tr>"
+"<td>"+message.user_id+": "+message.msg+"</td>"
+"</tr></table>");
}   
});

}
}

});
});
}

function saveMsg(obj)
{

var receiver=obj.parent().parent().find("#receiver").val();

var sender=$("#sender").val();
if(sender=='') return false;
var msg=obj.parent().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().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":
    $result=array('status'=>false,'data'=>array()); 
    $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();
    $messages=array();
    while ($row = $r->fetch_assoc()) {
        $messages[]=$row;
    }
    $result['status']=true;
    $result['data']['messages']=$messages;
    header('content-type:application/json');
    echo json_encode($result);
    break;
 
    case "get_chat":
    $result=array('status'=>false,'data'=>array());     
    $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();
    $users=array();
    while ($row = $r->fetch_assoc()) {
        $users[]=$row;
    }
    $result['status']=true;
    $result['data']['users']=$users;
    header('content-type:application/json');
    echo json_encode($result);
    break;
 
    case "view_users":
    $result=array('status'=>false,'data'=>array());
    $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();
    $users=array();
    while ($row = $r->fetch_assoc()) {       
        $users[]=$row;
    }
    $result['status']=true;
    $result['data']['users']=$users;
    header('content-type:application/json');
    echo json_encode($result);
 
    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 2

No comments:

Post a Comment

Search This Blog