Saturday, 14 July 2018

Create Dynamic Column Chart using PHP Ajax with Google Charts

If you have working on any web application and in that you want to display analytics data, so for display analytics data you want to use charts. For making dynamic charts from big data, so Google has provide rich and powerful charts library which is available free to use with any programming language. By using Google Charts Api we can use different type of charts like Column chart, bar chart, area chart, geo graphical chart and many more. So, we can use this all charts in our web application as per our requirement. Charts or Graph is a graphical representation of our dynamic data, so based on this Charts we can analyze data and can take decision. Most of management has take their decision based on Graphical representation of data which has been display in Graph format and this graph we will make by using Google charts library.

In this post we have use Google Chart library api and by using this Api we will make Column Charts from dynamic Mysql table data using Ajax with PHP PDO script. We have use Ajax with Google charts that means we will make Google Charts Column charts using Ajax call and in Ajax request which send request to PHP script for fetch data from Mysql database and converted into PHP array and then this PHP array data will be converted into JSON string. Because Google Charts has use JSON data for populate charts on web page. So here we have converted PHP array to JSON and this JSON data has been received by Ajax function. After receiving of dynamic data in JSON format. So, lastly we have to load this data into Google charts. On every Ajax function call it has fetch dynamic data in JSON format and make dynamic column chart on web page without refresh of web page.

If we have large amount of data and this data we want to make dynamic chart from data divided into different part. e.g. We have last 10 years of data and now we cannot display last 10 years data in single chart, so we can divided this data into year, so we can display every year data on web in chart format by using Ajax. So suppose we want to get second year data so we can simply select that year data from select box and on selection of year it will called Ajax call and it will fetch selected year data from Mysql database and received in json format and load into Google charts library. So this way we can make dynamic column chart for each year using Google charts library with Ajax and PHP.










Source Code


database_connection.php



<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");



?>


index.php



<?php  

//index.php

include("database_connection.php");

$query = "SELECT year FROM chart_data GROUP BY year DESC";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

?>  
<!DOCTYPE html>  
<html>  
    <head>  
        <title>Create Dynamic Column Chart using PHP Ajax with Google Charts</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
    </head>  
    <body> 
        <br /><br />
        <div class="container">  
            <h3 align="center">Create Dynamic Column Chart using PHP Ajax with Google Charts</h3>  
            <br />  
            
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div class="row">
                        <div class="col-md-9">
                            <h3 class="panel-title">Month Wise Profit Data</h3>
                        </div>
                        <div class="col-md-3">
                            <select name="year" class="form-control" id="year">
                                <option value="">Select Year</option>
                            <?php
                            foreach($result as $row)
                            {
                                echo '<option value="'.$row["year"].'">'.$row["year"].'</option>';
                            }
                            ?>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="panel-body">
                    <div id="chart_area" style="width: 1000px; height: 620px;"></div>
                </div>
            </div>
        </div>  
    </body>  
</html>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback();

function load_monthwise_data(year, title)
{
    var temp_title = title + ' '+year+'';
    $.ajax({
        url:"fetch.php",
        method:"POST",
        data:{year:year},
        dataType:"JSON",
        success:function(data)
        {
            drawMonthwiseChart(data, temp_title);
        }
    });
}

function drawMonthwiseChart(chart_data, chart_main_title)
{
    var jsonData = chart_data;
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Month');
    data.addColumn('number', 'Profit');
    $.each(jsonData, function(i, jsonData){
        var month = jsonData.month;
        var profit = parseFloat($.trim(jsonData.profit));
        data.addRows([[month, profit]]);
    });
    var options = {
        title:chart_main_title,
        hAxis: {
            title: "Months"
        },
        vAxis: {
            title: 'Profit'
        }
    };

    var chart = new google.visualization.ColumnChart(document.getElementById('chart_area'));
    chart.draw(data, options);
}

</script>

<script>
    
$(document).ready(function(){

    $('#year').change(function(){
        var year = $(this).val();
        if(year != '')
        {
            load_monthwise_data(year, 'Month Wise Profit Data For');
        }
    });

});

</script>



<?php

//fetch.php

include('database_connection.php');

if(isset($_POST["year"]))
{
 $query = "
 SELECT * FROM chart_data 
 WHERE year = '".$_POST["year"]."' 
 ORDER BY id ASC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'month'   => $row["month"],
   'profit'  => floatval($row["profit"])
  );
 }
 echo json_encode($output);
}

?>

Friday, 13 July 2018

15 Tips to Keep Your Phone in Good Condition

15 Tips to Keep Your Phone in Good Condition


Smartphones have become a necessity in modern day life since they are used to do anything which makes our lives easier and happier. With every passing day, smartphones are getting improvements and modifications which make them a must-have device for us. However, to get a great phone experience to a long extent, it is important to keep a smartphone in good physical and working condition. The following article aims to provide you with the best 15 tips to keep your phone in good condition. Take a look at them!

1. Get a Screen Protector


To keep dirt and dust off the screen, you can get a screen protector. These bits of debris can damage to your phone’s screen. As well, it offers maximum protection to your phone from any scratches or breakage. So, use your phone screen as normal and new through the screen protector.

If you have broken your iPhone screen, you should go for specialised iPhone repair services to get it back to life in a safe yet cheap way.

2. Buy a Case


To keep your phone protected and in a good condition, you should get a hard case that fits your phone perfectly. There are lots of cases for all smartphone brands available on the market, you can choose the one according to your preferences. Mobile covers not only take all the abuse on behalf of your phone but also add more beauty and charm to its looks.

3. Keep Your Phone Free of Moisture


Moisture and water are considered an enemy to your smartphone. So, don’t leave it in places that are high in moisture, such as bathrooms and swimming pools as they could end up causing damage. It is best that you leave it behind instead of risking water damage. You should also never handle your phone with wet hands. In any case of water damage, you should take it to a reputable Mobile phone repair shop for fixing it.



15 Tips to Keep Your Phone in Good Condition


4. Keep Your Phone Away from Heat.


Heat is the worst thing for your smartphone, not only it ruins your phone’s battery faster than just about anything else but also damages its looks. So, don’t leave it in a hot car or anywhere else in the direct sunshine.

5. Keep Your Mobile Cleaned


If you want to keep your phone in good condition, you should clean it regularly. To clean it, switch off your phone for safety, and then use the cleaning cloth that came with it. If it is not available, you can use any soft, lint-free cloth. Get it slightly moist but not wet. Never use any cleaning solvents, household cleaners, or alcohol etc.






6. Keep Your Battery in Top Condition


Keep your phone’s battery fully charged if you want to ensure the battery performance at peak. Don’t overcharge the battery and always charge your phone with original charger.

7. Handle Your Phone with Care


Smartphone screens are what we rely on to operate our phones. However, they are very delicate and prone to any breakage. So, to avoid any frustrating moments when the screen won’t respond to your touch, ensure that you always handle your handset with care. Avoid scratching and cracking it and get a cover with a handle that offers better grip to prevent falls that can be damaging to the screen and the phone as well.

8. Protect Your Phone From the Extreme Temperature


If you want to keep your smartphone protected, stay it away from the extreme weather conditions. Your phone’s screen is so sensitive and it can be cracked or broken if you leave it in the severe cold or hot area.

9. Don’t Download Apps and Media Files From Unreliable Sources


To ensure the perfect working condition of your phone, you should always download the applications and media files from reliable sources. If you don’t do that, the chances are that your phone gets infected by any viruses or malware that can damage your phone permanently.

10.

Don’t Use Your Phone While Charging It
Don’t forget to follow this tip if you want to improve your smartphone’s battery life, as well as, to run your phone as much faster as a new one.

11. Avoid Downloading Unnecessary Apps


Both Google and Apple Stores have millions of apps but you should only download the apps you need the most. Avoid downloading the unnecessary apps because they consume your phone’s memory, resulting your phone’s performances goes down.

12. Update the Phone OS


Whether you own an iPhone or an Android smartphone, update its operating system to the latest version. The latest versions of your device software generally come with bug fixes for better performance and enhanced security as well.

13. Charge Your Phone Optimally


If you want to enjoy a great phone experience, you should keep your phone charged optimally. Most experts say you should keep your phone charged between 40% to 80%. Therefore, you should try to charge it frequently at different times instead of daily charging to 100%. It helps you keep your phone’s battery healthy for a long period.

14. Your Smartphone Needs a Fresh Start


Smartphones are just like mini computers and need to be restarted every one or two days to get a fresh start. By doing so, they become much faster and smoother because all the glitches are fixed that can hinder the device’s performance. So, if you want to keep your phone working like a new one, try this tip regularly.

15. Try a New Launcher


If you are bored with your old phone and want to bring some charm to it back, you can simply try different themes and launchers to give it a new look. Android users can download the launchers from Google Play Store, while iOS users don’t have this option. Well, they can simply change the home screen and lock screen wallpapers and spend some time to organise their icons into folders to transform their phone’s looks.

Wednesday, 4 July 2018

Live Chat System in PHP using Ajax JQuery



Chat App is a favorite application which every programmer want to be make their own chat application in their programming career. This Chat application mostly used to communicate with friends and in business world company has communicate with their customer to provide assistant or help to customer regarding their services or product which they has offered. So, it is very important application which required in every website or web application. So, this type of system we have start to make in step by step process by using PHP script with Ajax Jquery Mysql Bootstrap and JQuery UI library.

Do you know real time chat application, real time chat application means we can communicate multiple person at the same time, so there are many business houses use a chat application for communicate with their customer in real time and provide services. For the importance of this chat system we have decided to publish tutorial on chat application in php and mysql using Ajax JQuery.

So, in this post we are going to make simple chat application by using Ajax Jquery and PHP programming and Mysql database. Ajax with Jquery script is used to send and received request for data from client machine to server and server to client machine using PHP. It is mainly used for create real time application for send and received data without refresh of web page. In the real web world, we have generally use HTTP request GET and POST method for communication done between client and server side. In this PHP Chat application we have use Ajax Jquery to communicate with the server. Below you can find complete step by step process for create Chat Application in PHP using Ajax.




Database Structure for PHP Ajax Chat Application


Here this is Mysql database structure for PHP Mysql chat system. Following tables we will use to make chat app.


--
-- Database: `chat`
--

-- --------------------------------------------------------

--
-- Table structure for table `chat_message`
--

CREATE TABLE `chat_message` (
  `chat_message_id` int(11) NOT NULL,
  `to_user_id` int(11) NOT NULL,
  `from_user_id` int(11) NOT NULL,
  `chat_message` text NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `status` int(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `login`
--

CREATE TABLE `login` (
  `user_id` int(11) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `login`
--

INSERT INTO `login` (`user_id`, `username`, `password`) VALUES
(1, 'johnsmith', '$2y$10$4REfvTZpxLgkAR/lKG9QiOkSdahOYIR3MeoGJAyiWmRkEFfjH3396'),
(2, 'peterParker', '$2y$10$4REfvTZpxLgkAR/lKG9QiOkSdahOYIR3MeoGJAyiWmRkEFfjH3396'),
(3, 'davidMoore', '$2y$10$4REfvTZpxLgkAR/lKG9QiOkSdahOYIR3MeoGJAyiWmRkEFfjH3396');

-- --------------------------------------------------------

--
-- Table structure for table `login_details`
--

CREATE TABLE `login_details` (
  `login_details_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `last_activity` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `is_type` enum('no','yes') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `chat_message`
--
ALTER TABLE `chat_message`
  ADD PRIMARY KEY (`chat_message_id`);

--
-- Indexes for table `login`
--
ALTER TABLE `login`
  ADD PRIMARY KEY (`user_id`);

--
-- Indexes for table `login_details`
--
ALTER TABLE `login_details`
  ADD PRIMARY KEY (`login_details_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `chat_message`
--
ALTER TABLE `chat_message`
  MODIFY `chat_message_id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `login`
--
ALTER TABLE `login`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `login_details`
--
ALTER TABLE `login_details`
  MODIFY `login_details_id` int(11) NOT NULL AUTO_INCREMENT;


Once you have make chat database and above table in your mysql database then you have to make database connection. For making database connection using PHP PDO we have to write following code.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat", "root", "");

?>


Make Login and Logout page for chat application using PHP and Jquery




Once you have make database connection then after we want to make login and logout page for our PHP Mysql Chat system. We all know Login into a system is one type of process in which an user can gain access into our web application by identifying their authenticating their identity to system. So here for using our Live Chat Application we have to make Login and logout process, so we can authenticating user identity and get access them to gain our chat application. And by clicking on logout link they can leave our Chat app. Below you can find login source code for this PHP Ajax Chat script.







<!--
//login.php
!-->

<?php

include('database_connection.php');

session_start();

$message = '';

if(isset($_SESSION['user_id']))
{
 header('location:index.php');
}

if(isset($_POST["login"]))
{
 $query = "
   SELECT * FROM login 
    WHERE username = :username
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
    array(
      ':username' => $_POST["username"]
     )
  );
  $count = $statement->rowCount();
  if($count > 0)
 {
  $result = $statement->fetchAll();
    foreach($result as $row)
    {
      if(password_verify($_POST["password"], $row["password"]))
      {
        $_SESSION['user_id'] = $row['user_id'];
        $_SESSION['username'] = $row['username'];
        $sub_query = "
        INSERT INTO login_details 
        (user_id) 
        VALUES ('".$row['user_id']."')
        ";
        $statement = $connect->prepare($sub_query);
        $statement->execute();
        $_SESSION['login_details_id'] = $connect->lastInsertId();
        header("location:index.php");
      }
      else
      {
       $message = "<label>Wrong Password</label>";
      }
    }
 }
 else
 {
  $message = "<label>Wrong Username</labe>";
 }
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Chat Application Login</div>
    <div class="panel-body">
     <form method="post">
      <p class="text-danger"><?php echo $message; ?></p>
      <div class="form-group">
       <label>Enter Username</label>
       <input type="text" name="username" class="form-control" required />
      </div>
      <div class="form-group">
       <label>Enter Password</label>
       <input type="password" name="password" class="form-control" required />
      </div>
      <div class="form-group">
       <input type="submit" name="login" class="btn btn-info" value="Login" />
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>


This is simple login page code for our PHP Chat application. Here we have authenticate user details like username and password. If this both details is proper then he can get access into this online chat system. Otherwise it will get wrong information error on web page. Suppose user has enter proper details then he can get access into our live chat app. Here we have store hash password in database, so for validate hash password we have use password_verify() function. By using this function this system can authenticate user password. After authenticate process particular user details like user id and user name has been store into $_SESSION variable and this variable value we can from accross system. Particular user login details like his user id and timestamp details has been inserted into login_details table. After inserting their login details into database then last inserted id of login_details table has been get by using lastInsertId() method and store into $_SESSION['login_details_id'] variable. This data will help use to know particular user online status like he is onlin and offline. So, this whole discussion of login table.

After login in Chat Application user will be redirect to index page. Below you can find index page source code. This page cannot access directly without login into system because for access this page we want to login into system. So, authenticated used can only access this page. For this here we have validate $_SESSION['user_id'] variable value. Here you can find logout page link also.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header('location:login.php');
}
?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username']; ?> - <a href="logout.php">Logout</a></p>
    
   </div>
  </div>
    </body>  
</html>  


Above code is index.php code and this page can be access only after login into Chat system. Here we can see logout link also. Once we have click on this link we will be logout from this system and page has been redirect to login.php page. Below you can find logout.php page code.


<?php

//logout.php

session_start();

session_destroy();

header('location:login.php');

?>


Display User Data in PHP Ajax Chat system




After complete discuss of login and logout source code. Now we have move to next stage of Chat Application development and this stag is display all user data on web page when user login into Chat application and after validate user data then he will redirect to index.php page. On this page we want to display all user data which are available in login table. So login user can decide to which person he want to login. In this step we have simple fetch user data from login table and display on index page. Below you can source code for display user details on web page.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }
 
});  
</script>



<?php

//fetch_user.php

include('database_connection.php');

session_start();

$query = "
SELECT * FROM login 
WHERE user_id != '".$_SESSION['user_id']."' 
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

$output = '
<table class="table table-bordered table-striped">
 <tr>
  <td>Username</td>
  <td>Status</td>
  <td>Action</td>
 </tr>
';

foreach($result as $row)
{
 $output .= '
 <tr>
  <td>'.$row['username'].'</td>
  <td></td>
  <td><button type="button" class="btn btn-info btn-xs start_chat" data-touserid="'.$row['user_id'].'" data-tousername="'.$row['username'].'">Start Chat</button></td>
 </tr>
 ';
}

$output .= '</table>';

echo $output;

?>


Here we have create one
tag with id="user_details" tag, under this tag it will display user detail table format. For fetch details, here we have make function which send ajax request to fetch_user.php page. This fetch user data and converted into html and send to ajax function which has been display on webpage.

Display Online / Offline User Status in Live chat application




This is next step of How to create chat application in PHP and in this step we have discuss how to display online and offline status of user in real time chat system using PHP Ajax. Because if login can see particular is online then he can chat with online user and he cam make chat conversation with him. For this we want to display particular user status is online or offline. Online user means, user has login into system and he has stay on index.php page. For this we have write following source code for check user is status is online or offline in chat application using PHP.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }
 
});  
</script>



<?php

//update_last_activity.php

include('database_connection.php');

session_start();

$query = "
UPDATE login_details 
SET last_activity = now() 
WHERE login_details_id = '".$_SESSION["login_details_id"]."'
";

$statement = $connect->prepare($query);

$statement->execute();

?>


First on index.php page we have make one function update_last_activity(), this function will ajax request to update_last_activity.php page for update login user last activity datatime details in login_details table. And this function we have called every 5 seconds by using setInterval() jquery method. Under this method we have also add fetch_user() function also. So on every 5 seconds this both function will be called, function will update login user datetime details under login_details table and second function fetch and display updated user details on webpage.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat", "root", "");

date_default_timezone_set('Asia/Kolkata');

function fetch_user_last_activity($user_id, $connect)
{
 $query = "
 SELECT * FROM login_details 
 WHERE user_id = '$user_id' 
 ORDER BY last_activity DESC 
 LIMIT 1
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['last_activity'];
 }
}

?>


After this on database_connection.php page we have make one function fetch_user_last_activity(). This function will fetch particular user last_activity datetime data from login_details table. So, by using this function we can get particular user last activity datetime, so we can check user is online or not in Live Chat App using Ajax with PHP. For this things we have some code at fetch_user.php file. Below you can find that source code.


<?php

//fetch_user.php

include('database_connection.php');

session_start();

$query = "
SELECT * FROM login 
WHERE user_id != '".$_SESSION['user_id']."' 
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

$output = '
<table class="table table-bordered table-striped">
 <tr>
  <td>Username</td>
  <td>Status</td>
  <td>Action</td>
 </tr>
';

foreach($result as $row)
{
 $status = '';
 $current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
 $current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
 $user_last_activity = fetch_user_last_activity($row['user_id'], $connect);
 if($user_last_activity > $current_timestamp)
 {
  $status = '<span class="label label-success">Online</span>';
 }
 else
 {
  $status = '<span class="label label-danger">Offline</span>';
 }
 $output .= '
 <tr>
  <td>'.$row['username'].'</td>
  <td>'.$status.'</td>
  <td><button type="button" class="btn btn-info btn-xs start_chat" data-touserid="'.$row['user_id'].'" data-tousername="'.$row['username'].'">Start Chat</button></td>
 </tr>
 ';
}

$output .= '</table>';

echo $output;

?>


Above code we can see, we have add some code for check particular user is online or offline. For this here first we have store current date time in one variable and and from this datetime we have minus 10 seconds. After this we have store single user last activity datetime has been get by fetch_user_last_activity() and store in one variable. Now we can compare user last activity datetime data with current datetime. If user last activity datetime value greater than current datetime value that means user is login into system and his status will be online and if user last activity datetime value less than current datetime then user status will be offline. So this way we can display user status online or offline in web server based Chat application in PHP.

Make Dynamic Chat Box for Each User in Ajax PHP Chat Application




Now we come to main discussion of PHP Ajax Chat Application and here we have one question how can we generated dynamic chat dialog box for each user. Because this is main part in this via this dialog box user can chat with each other. For this how can we make dynamic chat dialog box for each. For this we have make one jquery function on index.php. This function will dynamically generate html code for chat dialog box. Here for chat dialog box we have use JQuery UI Dialog box plugin. So, when we have called this function this function will generate html code for chat dialog box. Below you can find source code for generating of dynamic chat dialog box.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
    <div id="user_model_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }

 function make_chat_dialog_box(to_user_id, to_user_name)
 {
  var modal_content = '<div id="user_dialog_'+to_user_id+'" class="user_dialog" title="You have chat with '+to_user_name+'">';
  modal_content += '<div style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;" class="chat_history" data-touserid="'+to_user_id+'" id="chat_history_'+to_user_id+'">';
  modal_content += '</div>';
  modal_content += '<div class="form-group">';
  modal_content += '<textarea name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" class="form-control"></textarea>';
  modal_content += '</div><div class="form-group" align="right">';
  modal_content+= '<button type="button" name="send_chat" id="'+to_user_id+'" class="btn btn-info send_chat">Send</button></div></div>';
  $('#user_model_details').html(modal_content);
 }

 $(document).on('click', '.start_chat', function(){
  var to_user_id = $(this).data('touserid');
  var to_user_name = $(this).data('tousername');
  make_chat_dialog_box(to_user_id, to_user_name);
  $("#user_dialog_"+to_user_id).dialog({
   autoOpen:false,
   width:400
  });
  $('#user_dialog_'+to_user_id).dialog('open');
 });
 
});  
</script>


In Above source code which we have write index.php page. Here we can see make_chat_dialog_box() function. This function will generate chat dialog box for each user based on value of to_user_id and to_user_name argument. So, based on value of this both argument, this function will make dynamic chat dialog box for every user. Now when this function will be called, this function will be called when we have click on stat chat button. So here we can see jquery code in which we can see start chat button class .start_chat which is selector with click event. So when we have click on this button it will fetch value from data-touserid and data-tousername attribute and store in variable. After this it has called make_chat_dialog_box(to_user_id, to_user_name) function and it will make dynamic chat dialog box for particular user of which we have click on start chat button. So, this way we can make dynamic chat dialog box in our online chat application using PHP.

Insert Chat Message into Mysql Database




Once we have completed learning How can we create dynamic chat dialog box for our chat application in PHP. Now we want to know how can we insert chat message into database and display list of chat message in chat dialog box. So, when we have click on start chat button of any particular user then chat dialog box has been pop up on web page and in that box there is one textarea field in which we chat type chat message and click on send button then chat message will be inserted into database. After insert into database it will display all chat message conversation between two user will be display in chat dialog box without refresh of web page. Because it is a real time chat application which we have made by using PHP with Ajax. Below we can find source code of insert chat message into msyql database.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
    <div id="user_model_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }

 function make_chat_dialog_box(to_user_id, to_user_name)
 {
  var modal_content = '<div id="user_dialog_'+to_user_id+'" class="user_dialog" title="You have chat with '+to_user_name+'">';
  modal_content += '<div style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;" class="chat_history" data-touserid="'+to_user_id+'" id="chat_history_'+to_user_id+'">';
  modal_content += '</div>';
  modal_content += '<div class="form-group">';
  modal_content += '<textarea name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" class="form-control"></textarea>';
  modal_content += '</div><div class="form-group" align="right">';
  modal_content+= '<button type="button" name="send_chat" id="'+to_user_id+'" class="btn btn-info send_chat">Send</button></div></div>';
  $('#user_model_details').html(modal_content);
 }

 $(document).on('click', '.start_chat', function(){
  var to_user_id = $(this).data('touserid');
  var to_user_name = $(this).data('tousername');
  make_chat_dialog_box(to_user_id, to_user_name);
  $("#user_dialog_"+to_user_id).dialog({
   autoOpen:false,
   width:400
  });
  $('#user_dialog_'+to_user_id).dialog('open');
 });

 $(document).on('click', '.send_chat', function(){
  var to_user_id = $(this).attr('id');
  var chat_message = $('#chat_message_'+to_user_id).val();
  $.ajax({
   url:"insert_chat.php",
   method:"POST",
   data:{to_user_id:to_user_id, chat_message:chat_message},
   success:function(data)
   {
    $('#chat_message_'+to_user_id).val('');
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 });
 
});  
</script>

Here in index.php page we have write jquery script on send button which class is .send_chat as selector. So when we have click on send button in chat dialog box then it will execute this block of code. In this script we have fetch value of id attribute of this send button in which we have store user id to whom we have send message. After this we have fetch value of textarea in which we have write chat message. After this we have send ajax request to insert_chat.php page for insert chat message into mysql database. This page source code we can find below.


<?php

//insert_chat.php

include('database_connection.php');

session_start();

$data = array(
 ':to_user_id'  => $_POST['to_user_id'],
 ':from_user_id'  => $_SESSION['user_id'],
 ':chat_message'  => $_POST['chat_message'],
 ':status'   => '1'
);

$query = "
INSERT INTO chat_message 
(to_user_id, from_user_id, chat_message, status) 
VALUES (:to_user_id, :from_user_id, :chat_message, :status)
";

$statement = $connect->prepare($query);

if($statement->execute($data))
{
 echo fetch_user_chat_history($_SESSION['user_id'], $_POST['to_user_id'], $connect);
}

?>


Above source code for insert chat message into Mysql table. Here we have make simple insert query using PHP PDO and pass required data for insert into database. After insert into database we want to display all chat message conversation in chat dialog box. So we have to fetch chat data from database which source code we can find below.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat", "root", "");

date_default_timezone_set('Asia/Kolkata');

function fetch_user_last_activity($user_id, $connect)
{
 $query = "
 SELECT * FROM login_details 
 WHERE user_id = '$user_id' 
 ORDER BY last_activity DESC 
 LIMIT 1
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['last_activity'];
 }
}

function fetch_user_chat_history($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE (from_user_id = '".$from_user_id."' 
 AND to_user_id = '".$to_user_id."') 
 OR (from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."') 
 ORDER BY timestamp DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<ul class="list-unstyled">';
 foreach($result as $row)
 {
  $user_name = '';
  if($row["from_user_id"] == $from_user_id)
  {
   $user_name = '<b class="text-success">You</b>';
  }
  else
  {
   $user_name = '<b class="text-danger">'.get_user_name($row['from_user_id'], $connect).'</b>';
  }
  $output .= '
  <li style="border-bottom:1px dotted #ccc">
   <p>'.$user_name.' - '.$row["chat_message"].'
    <div align="right">
     - <small><em>'.$row['timestamp'].'</em></small>
    </div>
   </p>
  </li>
  ';
 }
 $output .= '</ul>';
 return $output;
}

function get_user_name($user_id, $connect)
{
 $query = "SELECT username FROM login WHERE user_id = '$user_id'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['username'];
 }
}



?>


For fetch chat conversation we have make fetch_user_chat_history() function in database_connection.php file. This function has fetch latest chat message from mysql database and return data in html format. Here we have make one another function get_user_name() this function has return username of particular user based on value of user_id. So, this two function has use for return chat message in html format and this data has been display under chat dialog box using Ajax. So, this way we have insert chat message into mysql database and then after display in chat dialog box using Ajax with PHP.

Auto Refresh Chat Message in PHP Chat Application




Once chat message has inserted into Mysql database then after we want to display chat message to sender and receiver in their chat history without refresh of web page. For this we have make two jquery function on index.php page. Below you can find source code of it.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
    <div id="user_model_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
  update_chat_history_data();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }

 function make_chat_dialog_box(to_user_id, to_user_name)
 {
  var modal_content = '<div id="user_dialog_'+to_user_id+'" class="user_dialog" title="You have chat with '+to_user_name+'">';
  modal_content += '<div style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;" class="chat_history" data-touserid="'+to_user_id+'" id="chat_history_'+to_user_id+'">';
  modal_content += fetch_user_chat_history(to_user_id);
  modal_content += '</div>';
  modal_content += '<div class="form-group">';
  modal_content += '<textarea name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" class="form-control"></textarea>';
  modal_content += '</div><div class="form-group" align="right">';
  modal_content+= '<button type="button" name="send_chat" id="'+to_user_id+'" class="btn btn-info send_chat">Send</button></div></div>';
  $('#user_model_details').html(modal_content);
 }

 $(document).on('click', '.start_chat', function(){
  var to_user_id = $(this).data('touserid');
  var to_user_name = $(this).data('tousername');
  make_chat_dialog_box(to_user_id, to_user_name);
  $("#user_dialog_"+to_user_id).dialog({
   autoOpen:false,
   width:400
  });
  $('#user_dialog_'+to_user_id).dialog('open');
 });

 $(document).on('click', '.send_chat', function(){
  var to_user_id = $(this).attr('id');
  var chat_message = $('#chat_message_'+to_user_id).val();
  $.ajax({
   url:"insert_chat.php",
   method:"POST",
   data:{to_user_id:to_user_id, chat_message:chat_message},
   success:function(data)
   {
    $('#chat_message_'+to_user_id).val('');
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 });

 function fetch_user_chat_history(to_user_id)
 {
  $.ajax({
   url:"fetch_user_chat_history.php",
   method:"POST",
   data:{to_user_id:to_user_id},
   success:function(data){
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 }

 function update_chat_history_data()
 {
  $('.chat_history').each(function(){
   var to_user_id = $(this).data('touserid');
   fetch_user_chat_history(to_user_id);
  });
 }

 $(document).on('click', '.ui-button-icon', function(){
  $('.user_dialog').dialog('destroy').remove();
 });
 
});  
</script>


Above we can see we have make two function like fetch_user_chat_history() and update_chat_history_data() function. First function fetch chat data from mysql table and display under chat history div tag of particular user dialog box. After this we have called this function into make_chat_dialog_box(). So when user click on start chat button then it will called make_chat_dialog_box() function for make dynamic chat dialog box and under this function will called fetch_user_chat_history() which fetch chat message of sender and receiver and display under chat dialog box chat history div tag.

For make live and real time chat application we have make update_chat_history_data() function, this function we have use each() jquery method on .chat_history div tag. So this method will fetch data-touserid of each div tag of this class and store under this to_user_id variable and then after it will called fetch_user_chat_history() function based on value of to_user_id variable. So this function will update chat history in all chat dialog box which we have open in web page. For live and real time chat system we have add this update_chat_history_data() function into setInterval() method. So this function will be executed on every 5 seconds and it will update chat history data on every 5 seconds on web page in each user chat dialog box.


<?php

//fetch_user_chat_history.php

include('database_connection.php');

session_start();

echo fetch_user_chat_history($_SESSION['user_id'], $_POST['to_user_id'], $connect);

?>


Above code has been executed when ajax request send request to this page. Here we have simply called fetch_chat_history() function which we have make under database_connection.php. This function will fetch sender and receiver chat data and converted into html format and send to Ajax request.

Make New Message Notification in Chat Application


When sender send chat message to receiver then at receiver web page new message notification must be display and display how many new message he has received. So this feature we have add into this PHP Ajax Chat Application. For this we have make one function in database_connection.php file which source code you can find below.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat", "root", "");

date_default_timezone_set('Asia/Kolkata');

function fetch_user_last_activity($user_id, $connect)
{
 $query = "
 SELECT * FROM login_details 
 WHERE user_id = '$user_id' 
 ORDER BY last_activity DESC 
 LIMIT 1
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['last_activity'];
 }
}

function fetch_user_chat_history($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE (from_user_id = '".$from_user_id."' 
 AND to_user_id = '".$to_user_id."') 
 OR (from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."') 
 ORDER BY timestamp DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<ul class="list-unstyled">';
 foreach($result as $row)
 {
  $user_name = '';
  if($row["from_user_id"] == $from_user_id)
  {
   $user_name = '<b class="text-success">You</b>';
  }
  else
  {
   $user_name = '<b class="text-danger">'.get_user_name($row['from_user_id'], $connect).'</b>';
  }
  $output .= '
  <li style="border-bottom:1px dotted #ccc">
   <p>'.$user_name.' - '.$row["chat_message"].'
    <div align="right">
     - <small><em>'.$row['timestamp'].'</em></small>
    </div>
   </p>
  </li>
  ';
 }
 $output .= '</ul>';
 $query = "
 UPDATE chat_message 
 SET status = '0' 
 WHERE from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."' 
 AND status = '1'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $output;
}

function get_user_name($user_id, $connect)
{
 $query = "SELECT username FROM login WHERE user_id = '$user_id'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['username'];
 }
}

function count_unseen_message($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE from_user_id = '$from_user_id' 
 AND to_user_id = '$to_user_id' 
 AND status = '1'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $count = $statement->rowCount();
 $output = '';
 if($count > 0)
 {
  $output = '<span class="label label-success">'.$count.'</span>';
 }
 return $output;
}



?>


Above we can see count_unseen_message() function which get number chat message is unread under chat message table for particular user. Here status '1' means message unread and once message has been read then status will be change to '0'. So this function will count unread message of receiver of partcular sender based on value of status. For change message status we have add update chat message query under fetch_user_chat_history() so when this function will called then it will change chat message to '0'. After this function has been called in fetch_user.php where we have fetch user details. So, it will display new message notification when it has fetch user details. So on every user row it will display any new message notification or not.


<?php

//fetch_user.php

include('database_connection.php');

session_start();

$query = "
SELECT * FROM login 
WHERE user_id != '".$_SESSION['user_id']."' 
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

$output = '
<table class="table table-bordered table-striped">
 <tr>
  <th>Username</th>
  <th>Status</th>
  <th>Action</th>
 </tr>
';

foreach($result as $row)
{
 $status = '';
 $current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
 $current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
 $user_last_activity = fetch_user_last_activity($row['user_id'], $connect);
 if($user_last_activity > $current_timestamp)
 {
  $status = '<span class="label label-success">Online</span>';
 }
 else
 {
  $status = '<span class="label label-danger">Offline</span>';
 }
 $output .= '
 <tr>
  <td>'.$row['username'].' '.count_unseen_message($row['user_id'], $_SESSION['user_id'], $connect).'</td>
  <td>'.$status.'</td>
  <td><button type="button" class="btn btn-info btn-xs start_chat" data-touserid="'.$row['user_id'].'" data-tousername="'.$row['username'].'">Start Chat</button></td>
 </tr>
 ';
}

$output .= '</table>';

echo $output;

?>


Here Above we have called count_unseen_message() function for display any new message notification for every user. If there is any new message notification then it will display new chat message notification otherwise it will not display notification. So this way we can display new message notification in Chat Application by using PHP with Ajax JQuery with Mysql.

Display Typing Notification to Receiver When Sender Start Type




Here we have add one more in out chat application and that is how can we display typing notification to receiver when sender has start type in his chat dialog box. We have mainly seen this type of feature in many social media site. So, here we have also add this functionality in building of chat application using PHP Ajax. For this we have add one table column with name is_type in login_details table with enum('no','yes') datatype. No means user is not type in his chat dialog box and yes means user is start type in his chat dialog box. When user login into chat system then this column value will be no and we will update this column value to yes when user has start write in his chat dialog box.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header("location:login.php");
}

?>

<html>  
    <head>  
        <title>Chat Application using PHP Ajax Jquery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Chat Application using PHP Ajax Jquery</a></h3><br />
   <br />
   
   <div class="table-responsive">
    <h4 align="center">Online User</h4>
    <p align="right">Hi - <?php echo $_SESSION['username'];  ?> - <a href="logout.php">Logout</a></p>
    <div id="user_details"></div>
    <div id="user_model_details"></div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){

 fetch_user();

 setInterval(function(){
  update_last_activity();
  fetch_user();
  update_chat_history_data();
 }, 5000);

 function fetch_user()
 {
  $.ajax({
   url:"fetch_user.php",
   method:"POST",
   success:function(data){
    $('#user_details').html(data);
   }
  })
 }

 function update_last_activity()
 {
  $.ajax({
   url:"update_last_activity.php",
   success:function()
   {

   }
  })
 }

 function make_chat_dialog_box(to_user_id, to_user_name)
 {
  var modal_content = '<div id="user_dialog_'+to_user_id+'" class="user_dialog" title="You have chat with '+to_user_name+'">';
  modal_content += '<div style="height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;" class="chat_history" data-touserid="'+to_user_id+'" id="chat_history_'+to_user_id+'">';
  modal_content += fetch_user_chat_history(to_user_id);
  modal_content += '</div>';
  modal_content += '<div class="form-group">';
  modal_content += '<textarea name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" class="form-control chat_message"></textarea>';
  modal_content += '</div><div class="form-group" align="right">';
  modal_content+= '<button type="button" name="send_chat" id="'+to_user_id+'" class="btn btn-info send_chat">Send</button></div></div>';
  $('#user_model_details').html(modal_content);
 }

 $(document).on('click', '.start_chat', function(){
  var to_user_id = $(this).data('touserid');
  var to_user_name = $(this).data('tousername');
  make_chat_dialog_box(to_user_id, to_user_name);
  $("#user_dialog_"+to_user_id).dialog({
   autoOpen:false,
   width:400
  });
  $('#user_dialog_'+to_user_id).dialog('open');
 });

 $(document).on('click', '.send_chat', function(){
  var to_user_id = $(this).attr('id');
  var chat_message = $('#chat_message_'+to_user_id).val();
  $.ajax({
   url:"insert_chat.php",
   method:"POST",
   data:{to_user_id:to_user_id, chat_message:chat_message},
   success:function(data)
   {
    $('#chat_message_'+to_user_id).val('');
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 });

 function fetch_user_chat_history(to_user_id)
 {
  $.ajax({
   url:"fetch_user_chat_history.php",
   method:"POST",
   data:{to_user_id:to_user_id},
   success:function(data){
    $('#chat_history_'+to_user_id).html(data);
   }
  })
 }

 function update_chat_history_data()
 {
  $('.chat_history').each(function(){
   var to_user_id = $(this).data('touserid');
   fetch_user_chat_history(to_user_id);
  });
 }

 $(document).on('click', '.ui-button-icon', function(){
  $('.user_dialog').dialog('destroy').remove();
 });

 $(document).on('focus', '.chat_message', function(){
  var is_type = 'yes';
  $.ajax({
   url:"update_is_type_status.php",
   method:"POST",
   data:{is_type:is_type},
   success:function()
   {

   }
  })
 });

 $(document).on('blur', '.chat_message', function(){
  var is_type = 'no';
  $.ajax({
   url:"update_is_type_status.php",
   method:"POST",
   data:{is_type:is_type},
   success:function()
   {
    
   }
  })
 });
 
});  
</script>


First we have on index.php page make_chat_dialog_box() function and in this function we have add .chat_message in the class attribute of textarea field. We will use this class attribute as a selector in jquery script. After this we have use this selector with jquery focus and blur event. Focus event means when cursor come into textarea field then this focus event code will execute at that time is_type variable value is equal to yes and this variable we have send to ajax request for update is_type table column value to yes. And on blur event when cursor leave from textarea field and at that time is_type variable value set to not and send this variable to ajax request for update is_type table column value set to no in PHP script.


<?php

//update_is_type_status.php

include('database_connection.php');

session_start();

$query = "
UPDATE login_details 
SET is_type = '".$_POST["is_type"]."' 
WHERE login_details_id = '".$_SESSION["login_details_id"]."'
";

$statement = $connect->prepare($query);

$statement->execute();

?>


This update_is_type_status.php page has received two ajax request at textarea field focus event and second request on textarea field blur event. In both event request has been send to this page for update value of is_type table column of login_details table. Now we want to fetch when particular user login_details table is_status column value is yes which source code we can find below.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=chat", "root", "");

date_default_timezone_set('Asia/Kolkata');

function fetch_user_last_activity($user_id, $connect)
{
 $query = "
 SELECT * FROM login_details 
 WHERE user_id = '$user_id' 
 ORDER BY last_activity DESC 
 LIMIT 1
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['last_activity'];
 }
}

function fetch_user_chat_history($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE (from_user_id = '".$from_user_id."' 
 AND to_user_id = '".$to_user_id."') 
 OR (from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."') 
 ORDER BY timestamp DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<ul class="list-unstyled">';
 foreach($result as $row)
 {
  $user_name = '';
  if($row["from_user_id"] == $from_user_id)
  {
   $user_name = '<b class="text-success">You</b>';
  }
  else
  {
   $user_name = '<b class="text-danger">'.get_user_name($row['from_user_id'], $connect).'</b>';
  }
  $output .= '
  <li style="border-bottom:1px dotted #ccc">
   <p>'.$user_name.' - '.$row["chat_message"].'
    <div align="right">
     - <small><em>'.$row['timestamp'].'</em></small>
    </div>
   </p>
  </li>
  ';
 }
 $output .= '</ul>';
 $query = "
 UPDATE chat_message 
 SET status = '0' 
 WHERE from_user_id = '".$to_user_id."' 
 AND to_user_id = '".$from_user_id."' 
 AND status = '1'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $output;
}

function get_user_name($user_id, $connect)
{
 $query = "SELECT username FROM login WHERE user_id = '$user_id'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  return $row['username'];
 }
}

function count_unseen_message($from_user_id, $to_user_id, $connect)
{
 $query = "
 SELECT * FROM chat_message 
 WHERE from_user_id = '$from_user_id' 
 AND to_user_id = '$to_user_id' 
 AND status = '1'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $count = $statement->rowCount();
 $output = '';
 if($count > 0)
 {
  $output = '<span class="label label-success">'.$count.'</span>';
 }
 return $output;
}

function fetch_is_type_status($user_id, $connect)
{
 $query = "
 SELECT is_type FROM login_details 
 WHERE user_id = '".$user_id."' 
 ORDER BY last_activity DESC 
 LIMIT 1
 "; 
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  if($row["is_type"] == 'yes')
  {
   $output = ' - <small><em><span class="text-muted">Typing...</span></em></small>';
  }
 }
 return $output;
}



?>


On database_connection.php file we have make one another function for fetch user typing status for this we have make fetch_is_type_status() function. This function will return value if particular user is_type table column value is yes. If any user is_type table column value is yes then we want to display on webpage.


<?php

//fetch_user.php

include('database_connection.php');

session_start();

$query = "
SELECT * FROM login 
WHERE user_id != '".$_SESSION['user_id']."' 
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

$output = '
<table class="table table-bordered table-striped">
 <tr>
  <th width="70%">Username</td>
  <th width="20%">Status</td>
  <th width="10%">Action</td>
 </tr>
';

foreach($result as $row)
{
 $status = '';
 $current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
 $current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
 $user_last_activity = fetch_user_last_activity($row['user_id'], $connect);
 if($user_last_activity > $current_timestamp)
 {
  $status = '<span class="label label-success">Online</span>';
 }
 else
 {
  $status = '<span class="label label-danger">Offline</span>';
 }
 $output .= '
 <tr>
  <td>'.$row['username'].' '.count_unseen_message($row['user_id'], $_SESSION['user_id'], $connect).' '.fetch_is_type_status($row['user_id'], $connect).'</td>
  <td>'.$status.'</td>
  <td><button type="button" class="btn btn-info btn-xs start_chat" data-touserid="'.$row['user_id'].'" data-tousername="'.$row['username'].'">Start Chat</button></td>
 </tr>
 ';
}

$output .= '</table>';

echo $output;

?>


For display sender typing message notification to receiver for this we have called fetch_is_type_status() function in fetch_user.php page along with display of username table column. This page send updated user data on every 5 seconds. So, on every 5 seconds this function will be called and it will display updated status on web page. So, this is the whole process for display sender typing notification on receiver web page. This will add additional functionality in our chat application.

If have learn How to create Chat application in PHP with Ajax JQuery Mysql Bootstrap and Jquery UI from this tutorial. If you have any query into tutorial, please comment your query in comment box. We will reply on that comment and solve any issue in this real time live chat application using PHP Ajax.

Remaining Source Code of Chat application in PHP using Ajax will be updated very soon.

Saturday, 30 June 2018

AngularJS Inline CRUD with PHP

Inline CRUD means perform Create, Read, Update and Delete records operation withing table grid. Inline Add, Edit and remove data operation we will be done by using AngularJS with PHP Mysql. In some of our post in which we have already discuss insert update delete mysql data by using Jquery Ajax with PHP. But now we want to make this by using AngularJS script. Live Inline CRUD has enrich web page in which we can add new records dynamically, edit or update existing data and delete or remove mysql records dynamically display remaining data on web page without refresh of web page by using AngularJS with PHP Mysql.

Fetch Data from Mysql and Display on Webpage using AngularJS with PHP




In Live Table CRUD operation first we want to fetch data from mysql table by using PHP with AngularJS and then after we want to display on webpage in tabular grid format with edit and delete button. For display data in table format we have ng-repeat directive of AngularJS. Here we can't use HTML5 contenteditable attribute because AngularJS not support this attribute. For this here when we have click on edit button then particular table row data must be converted into textbox format and edit and delete button converted into Save and cancel button. For this things we can do in AngularJS by using ng-template directive. By using this directive we can make dynamic html template for different purpose if we want to see only data then it will display in plain text format and if we want to edit data then it must be converted into textbox format. This feature we can make by using ng-template directive and by using ng-include directive we can set which template must be use in which event. So, this way we can fetch data from mysql table and load on web page in table format by using AngularJS with PHP.

Inline Table Insert or Add Data into Mysql using AngularJS with PHP




Inline Insert or Add data into Mysql means we have not to navigate form to some url and insert data and submit form and after submit page redirect to all data table page. But in table we will insert data into Mysql database by using AngularJS with PHP. For Inline table insert we will add blank table row with textbox field in start of table with Add button. So for insert data we have to fill data into inline table textbox field and click on submit button. After click on submit button data will be inserted or added into mysql table and display latest data on web page in tabular grid format without refresh of whole web page. But before inserting of data we want to validate user has filled data into textbox or not. For form validation we have to write some javascript code to validate if we have use Jquery but here we have use AngularJS. So for user has enter some data or not we have use AngularJS ng-required and ng-disabled directive. ng-required directive do some as HTML required attribute has do but it has not display any validation message on web page. But we have use ng-disabled directive on submit button then if we have not filled ng-required directive html field then this button will be disabled. But if user has filled all records then only it will enabled submit button. So this form validation we can perform by using this AngularJS ng-required and ng-disabled directive. Once user has filled form and click on Add button then data will be posted to PHP script and by using PHP script it will insert or add data into mysql table. So this way we can inline insert or add data into mysql database using PHP with AngularJS.

Inline Table Edit or Update Mysql Data using AngularJS with PHP




Inline editing or updating of Mysql data will create user simple action by allowing for edit or update grid tabular data in table itself without navigating page to other page for edit form field but we can dot edit or update of data operation on table grid. As we know we have not use contenteditable attribute of HTML, so how can we edit table data field. For editing purpose we have use ng-template directive of AngularJS. By using this directive we will convert plain text data of table data field into textbox field. So we can easily edit data. We can select dynamic template by using ng-include directive. By using this directive we can use dynamic template as per requirement. So by using this both directive of AngularJS when we have click on edit button then it will converted particular row data in editable textbox field with save and cancle button. So when we have click on edit button then that row data has been to php script for edit or update data. For send data from inline table to php script we have use ng-model directive of AngularJS. So this way we have perform inline edit or update of mysql table data by using AngularJS with PHP.

Inline Delete or remove mysql data using AngularJS with PHP




This is last operation of Inline CRUD by using AngularJS with PHP and in this we will see how can we delete or remove data from live table by using AngularJS with PHP. This is very process, for this we have to make single AngularJS function which will be executed when we have click on delete button of any particular row of data. When we have click on delete button then it will send request to PHP script delete data operation from Mysql Database. Once data has been remove then on webpage it will display remaining data on web page in tabular grid format.

So, this are the simple process of creating single page inline CRUD application by using AngularJS with PHP. In this application we can Create, Read, Update and Delete mysql data operation on single page without going to another page and all this operation will be perform without refresh of web page. Below you can find complete source of this AngularJS Inline Crud Application with PHP Mysql.


AngularJS Inline CRUD with PHP







Source Code


database_connection.php



<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

?>


index.php



<html>  
    <head>  
        <title>Inline Table Add Edit Delete using AngularJS in PHP Mysql</title>  
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>  
    </head>  
    <body>  
        <div class="container">  
   <br />
            <h3 align="center">Inline Table Add Edit Delete using AngularJS in PHP Mysql</h3><br />
   <div class="table-responsive" ng-app="liveApp" ng-controller="liveController" ng-init="fetchData()">
                <div class="alert alert-success alert-dismissible" ng-show="success" >
                    <a href="#" class="close" data-dismiss="alert" ng-click="closeMsg()" aria-label="close">&times;</a>
                    {{successMessage}}
                </div>
                <form name="testform" ng-submit="insertData()">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" ng-model="addData.first_name" class="form-control" placeholder="Enter First Name" ng-required="true" /></td>
                                <td><input type="text" ng-model="addData.last_name" class="form-control" placeholder="Enter Last Name" ng-required="true" /></td>
                                <td><button type="submit" class="btn btn-success btn-sm" ng-disabled="testform.$invalid">Add</button></td>
                            </tr>
                            <tr ng-repeat="data in namesData" ng-include="getTemplate(data)">
                            </tr>
                            
                        </tbody>
                    </table>
                </form>
                <script type="text/ng-template" id="display">
                    <td>{{data.first_name}}</td>
                    <td>{{data.last_name}}</td>
                    <td>
                        <button type="button" class="btn btn-primary btn-sm" ng-click="showEdit(data)">Edit</button>
                        <button type="button" class="btn btn-danger btn-sm" ng-click="deleteData(data.id)">Delete</button>
                    </td>
                </script>
                <script type="text/ng-template" id="edit">
                    <td><input type="text" ng-model="formData.first_name" class="form-control"  /></td>
                    <td><input type="text" ng-model="formData.last_name" class="form-control" /></td>
                    <td>
                        <input type="hidden" ng-model="formData.data.id" />
                        <button type="button" class="btn btn-info btn-sm" ng-click="editData()">Save</button>
                        <button type="button" class="btn btn-default btn-sm" ng-click="reset()">Cancel</button>
                    </td>
                </script>         
   </div>  
  </div>
    </body>  
</html>  
<script>
var app = angular.module('liveApp', []);

app.controller('liveController', function($scope, $http){

    $scope.formData = {};
    $scope.addData = {};
    $scope.success = false;

    $scope.getTemplate = function(data){
        if (data.id === $scope.formData.id)
        {
            return 'edit';
        }
        else
        {
            return 'display';
        }
    };

    $scope.fetchData = function(){
        $http.get('select.php').success(function(data){
            $scope.namesData = data;
        });
    };

    $scope.insertData = function(){
        $http({
            method:"POST",
            url:"insert.php",
            data:$scope.addData,
        }).success(function(data){
            $scope.success = true;
            $scope.successMessage = data.message;
            $scope.fetchData();
            $scope.addData = {};
        });
    };

    $scope.showEdit = function(data) {
        $scope.formData = angular.copy(data);
    };

    $scope.editData = function(){
        $http({
            method:"POST",
            url:"edit.php",
            data:$scope.formData,
        }).success(function(data){
            $scope.success = true;
            $scope.successMessage = data.message;
            $scope.fetchData();
            $scope.formData = {};
        });
    };

    $scope.reset = function(){
        $scope.formData = {};
    };

    $scope.closeMsg = function(){
        $scope.success = false;
    };

    $scope.deleteData = function(id){
        if(confirm("Are you sure you want to remove it?"))
        {
            $http({
                method:"POST",
                url:"delete.php",
                data:{'id':id}
            }).success(function(data){
                $scope.success = true;
                $scope.successMessage = data.message;
                $scope.fetchData();
            }); 
        }
    };

});

</script>


select.php



<?php  

//select.php
 
include('database_connection.php');

$query = "SELECT * FROM tbl_sample ORDER BY id DESC";
$statement = $connect->prepare($query);
if($statement->execute())
{
  while($row = $statement->fetch(PDO::FETCH_ASSOC))
  {
    $data[] = $row;
  }
  echo json_encode($data);
}

?>


insert.php



<?php  

//insert.php

include('database_connection.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$data = array(
 ':first_name'  => $form_data->first_name,
 ':last_name'  => $form_data->last_name
);

$query = "
 INSERT INTO tbl_sample 
 (first_name, last_name) VALUES 
 (:first_name, :last_name)
";

$statement = $connect->prepare($query);

if($statement->execute($data))
{
 $message = 'Data Inserted';
}

$output = array(
 'message' => $message
);

echo json_encode($output);

?>


edit.php



<?php  

//edit.php

include('database_connection.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$data = array(
 ':first_name'  => $form_data->first_name,
 ':last_name'  => $form_data->last_name,
 ':id'    => $form_data->id
);

$query = "
 UPDATE tbl_sample 
 SET first_name = :first_name, last_name = :last_name 
 WHERE id = :id
";

$statement = $connect->prepare($query);
if($statement->execute($data))
{
 $message = 'Data Edited';
}

$output = array(
 'message' => $message
);

echo json_encode($output);

?>


delete.php



<?php

//delete.php

include('database_connection.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$query = "DELETE FROM tbl_sample WHERE id = '".$form_data->id."'";

$statement = $connect->prepare($query);
if($statement->execute())
{
 $message = 'Data Deleted';
}

$output = array(
 'message' => $message
);

echo json_encode($output);

?>






Friday, 29 June 2018

Tips to Make & Save Money as a Student

Tips to Make & Save Money as a Student


Well, it’s a dream of almost every student to not only make money for himself but also to save it. But as he or she is studying so it’s difficult to make and save some pounds. Most of the students living in hostels, burn their cash in a matter of weeks. Living short of money is a nightmare for the students. During the shortage of money and having empty wallets, many students have to say goodbye to their luxury lifestyles. These students have to look for different ways to stretch their remaining money further for extra few days. As someone said that ‘Save Money and Money will Save you’.

There are a number of ways that you can adapt to help you in keeping your pockets full.

So here are some tips for the students that will help them in not only making money but also saving some pounds as well. So if you are a student and looking for some means to make and save money then bookmark this page because It’s time to get out of cheap beer budget. And don’t forget to comment on any method you know that can help the student community.

Gadgets purchase


Try to minimize your gadgets shopping to a possible level. If you don’t have a smartphone or it has been broken and you want to purchase a new one then remember to try not to purchase a brand new phone. Because it can costs you a lot of money. So it is recommended to get a used or refurbished mobile phone. There are a lot of mobile phone recycling companies that offer mobile phones in used and refurbished forms. So try to buy from these. By doing so, you can save a handsome amount (££).

Avoid outdoor eating


One of the very first steps to take in saving money is to avoid eating out. If you cook well, then it’s a great opportunity to cook at home and try to save your money from eating out. And whenever you go out for eating, then fast food is a prime choice for you rather than visiting upper-class restaurants and cafes.

Save Electricity


Saving electricity by turning off extra lights and other electric appliances can seriously save you a lot of money. Simple fixes can save you much amount in your leccy bills. Use energy saving bulbs. Turn off all the extra lights of your room. Don’t leave your room until you unplugged your gadgets that are not in use like a mobile phone charger or any other appliances.

Look for Part-time Job


If you are a student then employment has a lot of benefits for you. So it is highly advisable to look for a part-time job in your locality. If you are expert in anything then look for a job in that department so that you can maximize your efforts in that particular job. You can earn few hundred or even thousand pounds.

Bartending


Bartending is a go-to job for many students. Because it is easy to find work at local pubs. So if there is an opportunity comes, avail that!

Matched Betting


It is one of the quickest ways to make money and if the luck is with you, you can earn good amount of money through matched betting. It is absolutely legal and risk-free. Bundle of students have made £100s from matched betting.




Retailer Jobs


Retail jobs are another option for you available. And here is a quick tip for you, most of your colleagues will be seeking opportunities to work at university campus shops, you, on the other hand, should venture into your local area and you might find out work there. Websites like Gumtree can also help you identify places and businesses that are looking for new staff to hire.

Online Surveys


One of the increasingly popular ways among the students is to fill out online surveys. If you have spare time and don’t want to work outside then try online surveys by sitting at your sofa. Companies are always looking for new members to fill out their surveys and in return, you can make pounds. Some of the companies are MySurvey, The Opinion Panel, Harris Poll, IPSOS, Pinecone, SurveryBods, Hiving, Toluna, New Vista, iPoll.

Side Business


All of you must aware of Facebook, and how it came into being. If a university student can make world’ top social media site then there are also thousands of opportunities are available for you as well. So start working for yourself. Start selling your talent. If you are a website developer or a creative designer or a social media expert simply go to freelance websites and find out work for yourself.

Likewise, if you have language skills, find work for yourself as a tutor.

Don’t do shopping empty stomach


Remember the phrase… ‘His eyes were bigger than his stomach’. Exactly the same fits in this case if you are doing grocery shopping on an empty stomach. We suggest, try not to make impulse purchases having empty stomach.

Selling Stuff


If your stuff is no longer in use, then you can sell it to make few quid. There will be many things that you can sell including your old books, CDs, clothes etc.

Make a monthly budget


Calculate your income and expenses and make a monthly budget plan so that at the end of the month you don’t run out of money. Make your strict habit to stay in line with your budget plan.

Mystery Shopping


If you want to get rewarded handsomely than try to become a mystery shopper. It’s not a difficult job to do. All you have to do is to visit shops and restaurants and give feedback about their performance. There are many agencies and companies who will pay you for your feedback. Just Google about how to become a mystery shopper.

Sell you Notes


If you have notes then share them with other students to generate extra cash for yourself. You can also sell your notes to online sites like Notesale and Stuvia. Just upload your notes, set your price and when another student download your notes, you will get paid.

Affiliate Marketing


If you have a good presence on social media or own a website or blog, then you can start earning money by just promoting different products, services and offers online.