Sunday 16 September 2018

Load initial data into Django model

This article explains pre-populating or seeding the core tables in django with initial data. It may be helpful to insert tables like status,employee types automatically while port source code from one place to another. Example situations like copy code from development server to production server. You can provide this  initial data with migrations or fixtures.

Here I am explaining about load data using fixtures. A fixture is a collection of data that Django knows how to import into a database. Fixtures can be written as JSON, XML or YAML formats. This tutorial is based on JSON fixture. This tutorial is writing in django 2 but it works fine with django 1.11 also. I am using Ubuntu 16.

These are the steps ,first create a file named fixtures.json then write the data in json format, then run the command to write this data into database.

First, we need a django project. For that, create a directory named my_proj somewhere in your home directory. Open that folder, then open a terminal window in that location. Then run these commands to install Django.

virtualenv -p python3 env
source env/bin/activate
pip install Django


Then create a project named my_proj and app named my_app by run following commands

django-admin startproject my_proj .
django-admin startapp my_app


For detailed tutorial about installing Django locally, then create a project go to this link:- http://newprograminglogics.blogspot.com/2018/02/install-python-3-and-set-up-local.html

Open my_proj/my_proj/settings.py then add  'my_app' to the INSTALLED_APPS section. Now it will look like this

INSTALLED_APPS = [
         'django.contrib.admin',
         'django.contrib.auth',
         'django.contrib.contenttypes',
         'django.contrib.sessions',
         'django.contrib.messages',
         'django.contrib.staticfiles',
         'my_app'
]


The project is configured now. We need to create two sample models named Status and Employee_type.
For this add the following code in my_proj/my_proj/my_app/models.py

class Status(models.Model):
    name = models.CharField(max_length=200)
    meta_name = models.CharField(max_length=200)

    class Meta:
    db_table = 'status'



class Employee_type(models.Model):
    name = models.CharField(max_length=200)
    meta_name = models.CharField(max_length=200)

    class Meta:
    db_table = 'employee_type'


Run these commands to create the actual tables in the database.
python manage.py makemigrations
python manage.py migrate


Create a directory named fixtures in my_proj/my_proj/my_app directory. Then create a file named fixtures.json inside this directory.
Open this file and paste the following code in it


[
  {
    "model": "my_app.Status",
    "pk": 1,
    "fields": {
      "name": "Pending",
      "meta_name": "pending"
    }
  },
  {
    "model": "my_app.Status",
    "pk": 2,
    "fields": {
      "name": "Approved",
      "meta_name": "approved"
    }
  },
  {
    "model": "my_app.Status",
    "pk": 3,
    "fields": {
      "name": "Rejected",
      "meta_name": "rejected"
    }
  },


  {
    "model": "my_app.Employee_type",
    "pk": 1,
    "fields": {
      "name": "Admin",
      "meta_name": "admin"
    }
  },
  {
    "model": "my_app.Employee_type",
    "pk": 2,
    "fields": {
      "name": "Staff",
      "meta_name": "staff"
    }
  }
]



Look into the json data each element contains three fields named model,pk,fields. As the name says they are the model name, id of table row and fields of the table row respectively. In the model field the my_app represents the app name Status,Employee_type are the models.

Our fixture is ready now. Run this command to insert this fixture to the tables we created earlier
python manage.py loaddata fixtures.json


Here we are using sqlite db so open db.sqlite3 file in my_proj directory using a sqlite browser software.
Check the status and employee_type tables. The values provided in the fixtures.json is inserted into the tables.

You can download the example source code from here:-
https://dl.dropboxusercontent.com/s/dhrqxgkjuzlwze6/my_proj.zip

Watch the video tutorial here (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 

Thursday 2 August 2018

Django jwt authentication example with angular 5

When thinking about token authentication for our rest apis first think coming to our mind is JWT. JSON Web Token or JWT is a JSON-based open standard for creating access tokens that can use for purposes like rest api authentication.

This article contains a django application structure with jwt authentication, angular 5 and bootstrap 4 in front end.  This example uses django rest framework to create rest apis, and django-rest-framework-jwt for jwt authentication.

This example uses renowned professional angular 5 admin template SB admin. So it can be used as a starting point for your small or big scale projects. This example app will work fine with both Django 2 and 1.11 versions. I am using Ubuntu 16 for creating this example.

You can download the source code from this link:-
https://dl.dropboxusercontent.com/s/bd7bv2agd8y04q2/admin_proj.zip

Follow these steps to configure the example.
Download and extract the project. Then open a terminal window in the root directory of the project.

First, we need to create a virtual environment to run our project

For Django 1.11 run this command
virtualenv env


For Django 2 run this command
virtualenv -p python3 env


Then run the following command to activate the virtual environment
source env/bin/activate


Read this article for detailed description about creating virtual enviornments:- http://newprograminglogics.blogspot.com/2018/02/install-python-3-and-set-up-local.html

After that install django and related packages by run these commands

For Django 1.11
pip install certifi==2018.4.16
pip install Django==1.11
pip install django-cors-headers==2.4.0
pip install djangorestframework==3.8.2
pip install djangorestframework-jwt==1.11.0
pip install PyJWT==1.6.4
pip install pytz==2018.5


For Django 2
pip install certifi==2018.4.16
pip install Django==2.0.7
pip install  django-cors-headers==2.3.0
pip install djangorestframework==3.8.2
pip install djangorestframework-jwt==1.11.0
pip install PyJWT==1.6.4
pip install pytz==2018.5


Then run these to migrate database
python manage.py makemigrations
python manage.py migrate


Run this command to start django development server
python manage.py runserver


Make sure that the django development server is running at 8000 port.
Our backend is configured now.

Now open front_end directory in the project folder
open a terminal in that directory then run
npm install

Have any problems while install packages then use sudo

After all packages installed run
ng serve


Now the front end is available at http:127.0.0.1:4200
Open this in any browser. Click the register button, then create a user.
You can see the dashboard. Now start to add your custom functionalities.

Watch the video tutorial here (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



Saturday 23 June 2018

Integrate bootstrap template in Django 2

This article explains how to integrate a bootstrap  template in Django. I am using renowned bootstrap admin template SBAdmin in this tutorial.This tutorial is written in Ubuntu 16.04.

Watch the demo here:- (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



A bootstrap theme may have many dependencies like bootstrap library, jquery and other javascript plugins and css files.
So integrate these all to a Django project is something tricky.

We need to load the dependent libraries as static files. Then create parent templates for admin pages and normal pages. Copy body sections of each page in the template, then paste it into equivalent pages in our project. Then set view functions and urls correctly. I am explaining all these steps in this tutorial.
To download the full source file go to end of the tutorial.

First, create a directory named admin_proj somewhere in your home directory. Open that folder, then open a terminal window in that location. Then run these commands to install Django.

virtualenv -p python3 env
source env/bin/activate
pip install Django

Then create a project named admin_proj and app named admin_app by run following commands

django-admin startproject admin_proj .
django-admin startapp admin_app

For detailed tutorial about installing Django locally, then create a project go to this link:- http://newprograminglogics.blogspot.com/2018/02/install-python-3-and-set-up-local.html

Open admin_proj/admin_proj/settings.py then add  'admin_app' to the INSTALLED_APPS section.

Next open admin_proj/admin_proj/urls.py.
Add an include keyword in the line from django.urls import path

Now it will look like
from django.urls import path,include

Add this line in the urlpatterns section
path('admin_app/', include('admin_app.urls'))


Now download SBAdmin 2 template files from this link, https://github.com/BlackrockDigital/startbootstrap-sb-admin-2/archive/gh-pages.zip
Then extract the zip file.

It is the time to load these template files to our Django project as static files.
For this check following line is included in the INSTALLED_APPS section of admin_proj/admin_proj/settings.py
'django.contrib.staticfiles'

Then check this line is exist in the same settings.py file
STATIC_URL = '/static/'

Go to this link, for the detailed tutorial about load static files: -  http://newprograminglogics.blogspot.com/2018/03/load-static-files-in-django-20.html

Then create a folder named static in admin_app folder.
Create a folder named admin_app inside it. Then copy vendor,dist,data directories from the extracted SBAdmin directory to admin_proj/admin_app/static/admin_app directory.
Now the static directory will look like this
├── migrations
├── static
│   └── admin_app
│       ├── data
│       ├── dist
│       └── vendor

All js and css files are now in correct location. Now we can create some templates to display.

In the admin_app folder, create a folder named templates Create another folder named admin_app in it. I am going to create two base templates. One for admin pages with sidebar and header and another for login and regular pages without sidebar and header. Create a file named admin.html

Now the templates directory will look like this

├── migrations
├── static
├── templates
│   └── admin_app
│       ├── admin.html


Open index.html in pages directory of downloaded SBAdmin theme. Copy and paste the contents to admin.html. Delete the content inside the div with id "page-wrapper".

Now add the code inside "page-wrapper" div.
{% block content %}{% endblock %}


Our admin template is ready now. Now we can create a child html file to consume  this template.
Create a file named dashboard.html in the same location of admin.html. Once again open index.html in pages directory of downloaded SBAdmin theme. Copy the content inside "page-wrapper" div and paste to dashboard.html

Then add these line in top of the same file.
{% extends "admin_app/admin.html" %}
{% block content %}


Add this code at the bottom of the file
{% endblock %}

Now we are going to change the source url of script files.
../vendor/jquery/jquery.min.js should change to
{% static 'admin_app/vendor/jquery/jquery.min.js' %}


Similarly ../data/morris-data.js should change to
{% static 'admin_app/data/morris-data.js' %}


Do this for all js files and css files. You should add this line in the top of the file
{% load static %}


Copy all scripts into <head> section. Keep only common scripts and css like jquery.js and bootstrap.js in admin.html. Move other scripts like morris-data.js into dashboard.html. Because it is only needed on the dashboard page.

Add the same code at the top of dashboard.html also
{% load static %}


Then change the sidebar menu urls like this {% url 'admin_app:index' %} in admin.html.
This will create a url to localhost:8000/admin_app .We hadn't created any urls yet, but we will create it later.


Now we have created an admin.html template and a file named dashboard.html which consume the admin.html.
In the same way you can create equivalent pages for every page in the downloaded theme like buttons.html,forms.html, flot.html, gridhtml,icons.html etc.

In the same manner create another template named front_end.html and page named login.html from login.html page of downloaded theme.


Open admin_proj/admin_app/views.py. Then add this code
def index(request):
    return render(request, 'admin_app/dashboard.html')


This means the view function named index return the contents of dashboard.html. Similarly create functions for all other pages we created earlier.

Now create a file named urls.py in the same location of views.py, then add these code
from django.urls import path

from . import views

app_name = 'admin_app'
urlpatterns = [
    path('', views.index, name='index')
]


In this code path('', views.index, name='index') means that call to root url should call the index function in views.py.
Similarly, connect all views functions to equivalent urls.

Done we have successfully integrated a bootstrap template to Django. Now run python manage.py runserver, the open http:localhost:8000/admin_app in any browser.

If you don't have time to execute all the steps mentioned  above you can buy the example source  code from here:-  https://payhip.com/b/I3sTL

After download completed, extract the folder to somewhere on your computer, then open a terminal window inside the extracted project directory. Then run the following commands
virtualenv -p python3 env

source env/bin/activate

pip install django

python manage.py runserver


Then open http://127.0.0.1:8000/admin_app in any browser.


Tuesday 1 May 2018

Django chat application

This article is about how to create a chat application or chat server using Django 2.0. This chat system depends Python 3 and Django restframework to create rest apis. Jquery ajax is using to call the api from the client side. I am using Ubuntu 16.04 to create this tutorial.

You can download the example source code from here:- https://dl.dropboxusercontent.com/s/obt4u4udlt30k8w/chatproj.zip

After download completed, extract the folder to somewhere on your computer, then open a terminal window inside the extracted project directory. Then run the following commands to create a virtual environment and activate.

virtualenv -p python3 env

source env/bin/activate


For complete details about create a virtual environment read this article:- http://newprograminglogics.blogspot.com/2018/02/install-python-3-and-set-up-local.html

Then install Django by run this command
pip install django


Then install Django rest framework
pip install djangorestframework


Then run these commands to create migrations
python manage.py makemigrations chatapp

python manage.py migrate


All configurations completed. Now start the server using this command
python manage.py runserver


To check the functionality open http://127.0.0.1:8000/index in any browser
For reduce complexity I am not using a user login. You can simply login to chat by using your name or nickname without any log up process.

Enter your name like John , Peter in the From text box. Open the same url http://127.0.0.1:8000/index in another tab, type another name in it.
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.

Watch the video tutorial (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



Tuesday 6 March 2018

Load static files in django 2.0

This article is about how to serve static files in Django 2.0. Static files means javascript libraries like jquery, css files or images.
Jquery is an essential part of modern web development. When we use the templating system of django we need to do some steps to include jquery to it.
Sometimes you may try to access the static files by some methods it may not work properly and ends up in a 404 error.

I am explaining the process with an example application. This example includes a button. When click in it it will show an image.

This tutorial assumes that you have created a virual enviorment and django 2 project with mysite and app with myapp were created.
To read about how to create a virtual enviornment and install django go this link:- Install Python 3 and Set Up a Local Programming Environment

Open mysite/mysite/settings.py. Paste following line in the INSTALLED_APPS section
'myapp.apps.MyappConfig'


Then check following line is included in the INSTALLED_APPS section
'django.contrib.staticfiles'


Then check this line is exist in the same settings.py file
STATIC_URL = '/static/'


Then create a folder named static in myapp folder.
Create a folder named myapp inside it.
Download jquery and an image in this folder.

Then in the myapp folder create a folder named templates
Create another folder named myapp in it
Then create a file named index.html in it
Then paste the following code in it
{% load static %}
<!DOCTYPE html>
<html>
<body>
<img width="400px" height="300px" style="display:none;" id="img" src="{% static 'myapp/flower.jpg' %}"/>
<br/>
<input type="button" value="Show Image" id="btn"/>
<script src="{% static 'myapp/jquery-3.3.1.min.js' %}"></script>
<script>
$(document).ready(function(){
$('#btn').click(function(){
        $('#img').show();
});
});
</script>
</body>
</html>

Don't forget to add the line  {% load static %} in the top of the page.
In this code {% static 'myapp/flower.jpg' %} flower.jpg can replace with the image you downloaded in the static folder.
Also in {% static 'myapp/jquery-3.3.1.min.js' %} jquery-3.3.1.min.js can replace with your jquery version.

Open the file myapp/views.py
Paste the following code in it
def index(request):
    return render(request, 'myapp/index.html')


Create a file named urls.py in myapp folder
Then paste the following code in it
from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index')
]


Next open Open mysite/mysite/urls.py.
Add an include keyword in the line
from django.urls import path

Now it will look like
from django.urls import path,include


Add this line in the urlpatterns section
path('myapp/', include('myapp.urls'))


Then run the command in mysite folder
python manage.py runserver

Note that you must restart the development server in order to access static files.
Now open the url http://127.0.0.1:8000/myapp in any browser.It will show a button saying Show Image. Click it will show the image.

Watch the video tutorial (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



You can download the example app from here: https://dl.dropboxusercontent.com/s/zjssc3xgpzmxqnd/mysite.zip

Sunday 11 February 2018

Install Python 3 and Set Up a Local Programming Environment then install Django locally on Ubuntu 16.04

This article is about installing python 3 virtual environment on Ubuntu 16.04. If you are looking to set up a python 3 development environment, this  tutorial will help you.

First install python 3 by run these commands in the terminal
sudo apt-get install python3.5

Then install pip3 the python package manager by running
sudo apt-get install python3-pip

Then install virtualenv package
sudo pip3 install virtualenv

Then create a directory named my_proj which is our project name in your home directory. Then open a terminal window in that directory. Run the following command to create a virtual environment
virtualenv -p python3 env

Then run this command to activate the virtual environment
source env/bin/activate

Our virtual environment is activated now. To check it run
which python3

It will give the result    /home/sukesh/sukesh/python/my_proj/env/bin/python3

To install Django 2 run this
pip install Django

Note that pip, and python commands can be used in our virtual environment instead of pip3 and python3.

 Run this to check django
python -m django --version

It will give result   2.0.5

Create a sample project by run this. Don't forget the trailing dot(.)
django-admin startproject my_proj .

Our project is created now. Run this to create an app
django-admin startapp my_app

Now we need to add the created app to our project. For that open my_proj/my_proj/settings.py, then add 'my_app' to the INSTALLED_APPS section. Our INSTALLED_APPS will looks like this
INSTALLED_APPS = [
         'django.contrib.admin',
         'django.contrib.auth',
         'django.contrib.contenttypes',
         'django.contrib.sessions',
         'django.contrib.messages',
         'django.contrib.staticfiles',
         'my_app'
]


You have finished. To start the development server run
python manage.py runserver

Our server has started now. To check this open this url in any browser:-  http://127.0.0.1:8000

Watch this video tutorial (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)

Thank You

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)

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

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

Search This Blog