Thursday 31 March 2016

Use Ajax with Jquery in PHP to check Session Expired



In this post we are going to learn how to use Ajax with Jquery to check expired php session. I teach this tutorial will absolutely effective to lots of website developer who work on session based websites. When suppose user open website in more than one tab and suppose user logout from one tab and on other tab suppose user open website page then at that time this functionality used. If we used ajax with jquery to check session has expired or not. If session has expired then alert message your session has expired will appear on that tab where website open. I have used setInterval() method for execute function on regular time interval. I have make one function and in this function I have used ajax function call with the help of ajax function it will check session has expired or not.



Source Code


index.php


<!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial</title> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
           <style>  
                #box  
                {  
                     width:600px;  
                     background:gray;  
                     color:white;  
                     margin:0 auto;  
                     padding:10px;  
                     text-align:center;  
                }  
           </style>  
      </head>  
      <body>  
      <?php  
      session_start();  
      if(isset($_SESSION["name"]))  
      {  
          echo "<h1 align='center'>Use Ajax with Jquery in PHP to check Session Expired</h1>";
           echo "<h1 align='center'>".$_SESSION["name"]."</h1>";  
           echo "<p align='center'><a href='logout.php'>Logout</a></p>";  
      }  
      else  
      {  
           header('location:login.php');  
      }  
      ?>  
      </body>  
 </html>  
 <!--index.php !-->  
 <script>  
 $(document).ready(function(){  
       function check_session()
       {
          $.ajax({
            url:"check_session.php",
            method:"POST",
            success:function(data)
            {
              if(data == '1')
              {
                alert('Your session has been expired!');  
                window.location.href="login.php";
              }
            }
          })
       }
        setInterval(function(){
          check_session();
        }, 10000);  //10000 means 10 seconds
 });  
 </script>

login.php


<?php  
 //login.php  
 $connect = mysqli_connect("localhost", "root", "", "testing");
 session_start();  
 if(isset($_POST["sub"]))  
 {  
   $username = mysqli_real_escape_string($connect, $_POST["name"]);
   $password = mysqli_real_escape_string($connect, $_POST["pass"]);
   $query = "SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."'";
   $result = mysqli_query($connect, $query);
   if(mysqli_num_rows($result) > 0)
   {
    $_SESSION["name"] = $_POST["name"];
    header("location:index.php"); 
   }
      else
   {
    echo '<script>alert("Wrong Data")</script>';
   }    
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial</title> 
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
           <style>  
                #box  
                {  
                     width:600px;  
                     background:gray;  
                     color:white;  
                     margin:0 auto;  
                     padding:10px;  
                     text-align:center;  
                     margin-top:100px;
                }  
           </style>  
      </head>  
      <body>  
           <div id="box">
                <h1 align="center">Use Ajax with Jquery in PHP to check Session Expired</h1>  
                <h2>Login</h2>  
                <form method="post">  
                     <input type="text" name="name" id="name" placeholder="Enter Username" class="form-control" /><br />  
                     <input type="password" name="pass" id="pass" placeholder="Enter Pass" class="form-control" /><br />  
                     <input type="submit" name="sub" id="sub" class="btn btn-info" value="Submit" />  
                </form>  
                <br /><br />  
           </div>  
      </body>  
 </html>

logout.php


<?php  
 //logout.php  
 session_start();  
 session_destroy();  
 header('location:login.php');  
 ?>

check_session.php


<?php  
 //check_session.php  
 session_start();
 if(isset($_SESSION["name"]))  
 {  
      echo '0';     //session not expired       
 }  
 else  
 {  
      echo '1';     //session expired  
 }
 ?>

Wednesday 30 March 2016

How to Enter PHP Array within MySQL Database



This post is newcomer tutorial of PHP and MySQL. In This blog we will study how to enter php array within mysql database table. This is really natural issue when we have various rows of input data that we need to inserting within mysql as row.We can execute really efficiently using php to add array within mysql database. When you are working on some eCommerce website and you have store multiple item order array into session and when buyer want to place final order then at that time multiple item order array want to insert into order table then at that time this things required and I want to insert php array into mysql table.

There are two ways we add php array into mysql table database.

1) Insert PHP Array within MySql Using repeated Insert Query.

2) Insert PHP Array within MySql Database by applying Single Insert Query



Source Code

array_insert.php


 <?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $order_array = array(  
      "0"     =>     array("Mobile Phone", "1", "5000"),  
      "1"     =>     array("Power Bank", "1", "500"),  
      "2"     =>     array("Selfi Stick", "1", "250")  
 );  
 //Repetitive Insert command on each row  
 function option1($array, $connect)  
 {  
      if(is_array($array))  
      {  
           foreach($array as $row => $value)  
           {  
                $item_name = mysqli_real_escape_string($connect, $value[0]);  
                $qty = mysqli_real_escape_string($connect, $value[1]);  
                $price = mysqli_real_escape_string($connect, $value[2]);  
                $sql = "INSERT INTO tbl_order(item_name, qty, price) VALUES ('".$item_name."', '".$qty."', '".$price."')";  
                mysqli_query($connect, $sql);  
           }  
      }  
 }  
 option2($order_array, $connect); //Call Function  
 //Single Insert command by concatenating all array values into array  
 function option2($array, $connect)  
 {  
      if(is_array($array))  
      {  
           $values = array();  
           foreach($array as $row => $value)  
           {  
                $item_name = mysqli_real_escape_string($connect, $value[0]);  
                $qty = mysqli_real_escape_string($connect, $value[1]);  
                $price = mysqli_real_escape_string($connect, $value[2]);  
                $values[] = "('$item_name', '$qty', '$price')";  
           }  
           $sql = "INSERT INTO tbl_order(item_name, qty, price) VALUES ";  
           $sql .= implode(', ', $values);  
           mysqli_query($connect, $sql);  
      }  
 }  
 ?>  

Monday 28 March 2016

Use Marquee tag with PHP and Mysql - PHP Tutorial



In this post we are going to learn how to use Marquee tag with PHP and Mysql. Marquee tag is used to display scrolling text in up and down, right and left direction on web page. With the help of PHP programming language and Mysql database we can scrolling dynamic text in marquee tag. For stopping moving text we can write this code - onmouseover="this.stop();" and suppose friends If you want to again start moving text you can use this code - onmouseout="this.start();". You can also set the scrolling speed in attribute like scrollamout by entering number in this attribute. By using php and mysql we can easily fetch data from database table and display under marquee tag. Here we can display latest post or news by writing proper sql query. Implementation of this things is very easy and it is easy to understand.

Source Code


marquee.php


 <?php   
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $sql = "SELECT * FROM tbl_video ORDER BY video_id LIMIT 5";  
 $result = mysqli_query($connect, $sql);  
 ?>  
 <html>  
      <head>  
           <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
           <meta charset="utf-8">  
           <title>Webslesson Tutorial</title>  
           <script src="jquery.js"></script>  
           <script src="js/bootstrap.js"></script>  
           <link href="css/bootstrap.css" rel="stylesheet" />  
      </head>  
      <body>  
           <div class="container" style="width:500px; border:1px solid #ccc;">  
                <br />  
                <marquee behavior="scroll" direction="up" onmouseover="this.stop();" onmouseout="this.start();">  
                <?php  
                     if(mysqli_num_rows($result) > 0)  
                     {  
                          while($row = mysqli_fetch_array($result))  
                          {  
                               echo '<label><a href="'.$row['video_link'].'" target="_blank">'.$row['video_title'].'</a></label>';  
                          }  
                     }  
                ?>  
                </marquee>  
                <br />                 
           </div>  
      </body>  
 </html>  

Saturday 26 March 2016

How To Create A Show Hide Password Button using Jquery




In this tutorial we are going to learn how to create show hide password button using jquery. In most of the website's login or register page for reducing typo error while entering password, there is one more textbox for entering confirm password and re enter password. But this is old method. Now There is other alternative for reducing typo error while entering password we can show password after entering password. If we show password then we can reduce typo error. For showing password, I have used jquery. With the help of jquery we can show entering password and hide entering password on button click event. For show and hide entering password I have used jquery attr() method. This is very useful functionality for any website register or login page.



Online Demo



Login







Source Code


login.php



<html>  
 <head>  
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
  <meta charset="utf-8">  
  <title>Webslesson Tutorial</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
 </head>  
 <body>  
  <div class="container" style="width:500px; border:1px solid #ccc;">  
   <br />  
   <h2 align="center">Login</h2>  
   <form id="login_form">  
    <label>Username</label>  
    <input type="text" name="username" id="username" placeholder="Username" class="form-control" />  
    <br />  
    <label>Password</label>  
    <input type="password" name="password" id="password" placeholder="Password" class="form-control" />  
    <br />  
    <button type="button" id="show_password" name="show_password" class="btn btn-default">Show Password</button>  
   </form>  
   <br />                 
  </div>  
 </body>  
</html>  
<script>  
$(document).ready(function(){  
 $('#show_password').on('click', function(){  
  var passwordField = $('#password');  
  var passwordFieldType = passwordField.attr('type');
  if(passwordField.val() != '')
  {
   if(passwordFieldType == 'password')  
   {  
    passwordField.attr('type', 'text');  
    $(this).text('Hide Password');  
   }  
   else  
   {  
    passwordField.attr('type', 'password');  
    $(this).text('Show Password');  
   }
  }
  else
  {
   alert("Please Enter Password");
  }
 });  
});  
</script>

Friday 25 March 2016

How to Search for Exact word match FROM String using RLIKE



In this post we are going to learn on mysql query like how to search exact word match from string using RLIKE operator. If you have basic knowledge of mysql select query with where clause then you can easily understand what I want to teach you. When I working on one project then I have face one problem. The problem is that I have to search data from database where exact word is present in a given string. Exact word means suppose I want to search data where word 'Bla' present in given table string. That means I want to get that data in which column string has only 'Bla' word not 'Bla-123', '56-Bla', '12Bla56' etc. Only word 'Bla' present in a string.

So, Friends First I have used Where clause in Select query and try to get result but it not return any row. After this I have used wildcard LIKE operator and write query with using LIKE operator but it data with 'Bla' word but it also return that data with word like 'Bla-123', '56-Bla', '12Bla56'. So, Problem is not solve with LIKE operator.

 SELECT * FROM tbl_supplier WHERE sup_sub_industry_id LIKE '%4%';  



After this I have used RLIKE wildcards operator in my query. And I write this query.

 SELECT * FROM tbl_supplier where sup_sub_industry_id RLIKE '[[:<:]]4[[:>:]]';  

With help of this query I had get right result of data and I solve my problem. Here in this query "[[:<:]]" means substitute characters in the string BEGINING and "[[:>:]]" means substitute characters in the string END.

Wednesday 23 March 2016

Upload Resize Image using Ajax Jquery PHP without Page Refresh



In this post we are going to learn Ajax upload and resize an Image using PHP and Jquery. In this I have used Jquery FormData() Object with Ajax for upload image without page refresh. When User upload image to server then at that time page will not be refresh and after completing image upload it will display image on the web page without page refresh. In Now a days most of the social media sites like facebook, twitter using this functionality like upload image without page refresh. I have make some validation for uploading image. Validation like image is selected or not, allowed image file formate, size of image. If this validation pass image file then after it will upload to server without page refresh. I have used some php image function like getimagesize() function for getting width and height of uploaded image, imagecreatefrompng() function for create new image if png image, imagecreatefromjpeg() function for create new image from if image file is jpg or jpeg. For resize I have define new width and to maintain aspect ratio I have divide height by width into new height. I have also used other php image function like imagecreatetruecolor() function for create blank image, imagecopyresampled() function is copy portion of source image to destination image, imagejpeg() function is used for create image new image and last is imagedestroy image is used for destroy image from memory.



Source Code


index.php



<html>  
 <head>  
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
  <meta charset="utf-8">  
  <title>Webslesson Tutorial</title>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
 </head>  
 <body>  
  <div class="container">  
   <br />  
   <br />  
   <h3>Upload & Resize Image using Ajax Jquery PHP without Page Refresh</h3><br />  
   <form method="post" id="upload_image" enctype="multipart/form-data">
    <label>Select File <br />  
    <input type="file" name="image_upload" id="image_upload" />
    <br />
    <input type="submit" name="upload" id="upload" class="btn btn-info" value="Upload" />
   </form>
   <br />  
   <br />  
   <div id="preview"></div>  
   <br />  
   <br />  
  </div>  
 </body>  
</html>  
<script>  
$(document).ready(function(){   
    $('#upload_image').on('submit', function(event){
     event.preventDefault();
     $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      contentType:false,
      cache:false,
      processData:false,
      success:function(data){
       $('#preview').html(data);
      }
     })
    });
});  
</script>


upload.php



<?php  
//upload.php;
if(isset($_FILES["image_upload"]["name"])) 
{
 $name = $_FILES["image_upload"]["name"];
 $size = $_FILES["image_upload"]["size"];
 $ext = end(explode(".", $name));
 $allowed_ext = array("png", "jpg", "jpeg");
 if(in_array($ext, $allowed_ext))
 {
  if($size < (1024*1024))
  {
   $new_image = '';
   $new_name = md5(rand()) . '.' . $ext;
   $path = 'upload/' . $new_name;
   list($width, $height) = getimagesize($_FILES["image_upload"]["tmp_name"]);
   if($ext == 'png')
   {
    $new_image = imagecreatefrompng($_FILES["image_upload"]["tmp_name"]);
   }
   if($ext == 'jpg' || $ext == 'jpeg')  
            {  
               $new_image = imagecreatefromjpeg($_FILES["image_upload"]["tmp_name"]);  
            }
            $new_width=200;
            $new_height = ($height/$width)*200;
            $tmp_image = imagecreatetruecolor($new_width, $new_height);
            imagecopyresampled($tmp_image, $new_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($tmp_image, $path, 100);
            imagedestroy($new_image);
            imagedestroy($tmp_image);
            echo '<img src="'.$path.'" />';
  }
  else
  {
   echo 'Image File size must be less than 1 MB';
  }
 }
 else
 {
  echo 'Invalid Image File';
 }
}
else
{
 echo 'Please Select Image File';
}
?>

Monday 21 March 2016

Facebook style time ago function using PHP



In this tutorial we are going to learn how to make Facebook style time ago function in PHP. Friends If you have used Facebook and you update status on your wall or you upload photo on your Facebook wall then after uploading it display time as Just Now or you can also see your previous post time, it show like one week or month or year or day. In this tutorial we will learn how to come this type of time using php programming language. This is a very simple php script of get output like Facebook style time ago. In this function we can calculate time using particular country timezone. If you have previous date and time then in this function it count time between current date and time to this previous date time on simple php logic. In this function I convert previous date and time to UNIX time stamp and current date and time also get in UNIX time. From difference of this current UNIX time stamp and previous date and time time stamp we can get number of seconds between these date and time. From seconds we can easily get minutes, hours, days, weeks, months and years. In this post I also provide source code with this post.



Source Code

facebook_time_ago.php

 <?php  
 date_default_timezone_set('America/New_York');  
 echo facebook_time_ago('2016-03-11 04:58:00');  
 function facebook_time_ago($timestamp)  
 {  
      $time_ago = strtotime($timestamp);  
      $current_time = time();  
      $time_difference = $current_time - $time_ago;  
      $seconds = $time_difference;  
      $minutes      = round($seconds / 60 );           // value 60 is seconds  
      $hours           = round($seconds / 3600);           //value 3600 is 60 minutes * 60 sec  
      $days          = round($seconds / 86400);          //86400 = 24 * 60 * 60;  
      $weeks          = round($seconds / 604800);          // 7*24*60*60;  
      $months          = round($seconds / 2629440);     //((365+365+365+365+366)/5/12)*24*60*60  
      $years          = round($seconds / 31553280);     //(365+365+365+365+366)/5 * 24 * 60 * 60  
      if($seconds <= 60)  
      {  
     return "Just Now";  
   }  
      else if($minutes <=60)  
      {  
     if($minutes==1)  
           {  
       return "one minute ago";  
     }  
     else  
           {  
       return "$minutes minutes ago";  
     }  
   }  
      else if($hours <=24)  
      {  
     if($hours==1)  
           {  
       return "an hour ago";  
     }  
           else  
           {  
       return "$hours hrs ago";  
     }  
   }  
      else if($days <= 7)  
      {  
     if($days==1)  
           {  
       return "yesterday";  
     }  
           else  
           {  
       return "$days days ago";  
     }  
   }  
      else if($weeks <= 4.3) //4.3 == 52/12  
      {  
     if($weeks==1)  
           {  
       return "a week ago";  
     }  
           else  
           {  
       return "$weeks weeks ago";  
     }  
   }  
       else if($months <=12)  
      {  
     if($months==1)  
           {  
       return "a month ago";  
     }  
           else  
           {  
       return "$months months ago";  
     }  
   }  
      else  
      {  
     if($years==1)  
           {  
       return "one year ago";  
     }  
           else  
           {  
       return "$years years ago";  
     }  
   }  
 }  
 ?>  

Friday 18 March 2016

How to Use Ajax with PHP for login with shake effect



In this tutorial we are going to learn How to Use Ajax with PHP for login with shake effect. If you have used wordpress, then in wordpress login page if you have enter wrong login information then login form will be shake. So, this type of things will be learn here. For this things I have make one table for storing user information like username and password. For this things I have used jquery javascript library and jquery ui library for shake effect. Shake is a one effect method of jquery ui library. If you are beginner programmer then this a new things for you and you will be learn new things from here. I have used ajax functionality for login into site. Ajax will provide extra functionality to your site appearance. Because when user log into site then without page refresh home screen will appear. When user enter wrong data then shake effect will be run and shown on the web page. I have also provide source code with this post.


Source Code


index.php


<?php
//index.php
session_start();
if(isset($_SESSION["username"]))
{
 header("location:home.php");
}
?>
<html>
 <head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <title>Webslesson Tutorial</title>
  <script src="http://code.jquery.com/jquery-2.1.1.js"></script>
  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
  #box
  {
   width:100%;
   max-width:500px;
   border:1px solid #ccc;
   border-radius:5px;
   margin:0 auto;
   padding:0 20px;
   box-sizing:border-box;
   height:270px;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <h2 align="center">How to Use Ajax with PHP for Login with Shake Effect</h2><br /><br />
   <div id="box">
    <br />
    <form method="post">
     <div class="form-group">
      <label>Username</label>
      <input type="text" name="username" id="username" class="form-control" />
     </div>
     <div class="form-group">
      <label>Password</label>
      <input type="password" name="password" id="password" class="form-control" />
     </div>
     <div class="form-group">
      <input type="button" name="login" id="login" class="btn btn-success" value="Login" />
     </div>
     <div id="error"></div>
    </form>
    <br />
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $('#login').click(function(){
  var username = $('#username').val();
  var password = $('#password').val();
  if($.trim(username).length > 0 && $.trim(password).length > 0)
  {
   $.ajax({
    url:"login.php",
    method:"POST",
    data:{username:username, password:password},
    cache:false,
    beforeSend:function(){
     $('#login').val("connecting...");
    },
    success:function(data)
    {
     if(data)
     {
      $("body").load("home.php").hide().fadeIn(1500);
     }
     else
     {
      var options = {
       distance: '40',
       direction:'left',
       times:'3'
      }
      $("#box").effect("shake", options, 800);
      $('#login').val("Login");
      $('#error').html("<span class='text-danger'>Invalid username or Password</span>");
     }
    }
   });
  }
  else
  {

  }
 });
});
</script>

login.php


<?php
//login.php
session_start();
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["username"]) && isset($_POST["password"]))
{
 $username = mysqli_real_escape_string($connect, $_POST["username"]);
 $password = md5(mysqli_real_escape_string($connect, $_POST["password"]));
 $sql = "SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."'";
 $result = mysqli_query($connect, $sql);
 $num_row = mysqli_num_rows($result);
 if($num_row > 0)
 {
  $data = mysqli_fetch_array($result);
  $_SESSION["username"] = $data["username"];
  echo $data["username"];
 }
}
?>

home.php


<html>
 <head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <title>Webslesson Tutorial</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <?php
   //home.php
   session_start();
   if(!isset($_SESSION["username"]))
   {
    header("location: index.php");
   }
   echo '<h1 align="center">'.$_SESSION["username"].' - Welcome to Home Page</h1>';
   echo '<p align="center"><a href="logout.php">Logout</a></p>';
   ?>
  </div>
 </body>
</html>

logout.php


<?php
//logout.php
session_start();
session_destroy();
header("location:index.php");
?>

Tuesday 15 March 2016

Auto Save Data using Ajax, Jquery, PHP and Mysql


In this post we are going to learn how to save data automatically in database on specific time interval using Ajax Jquery with PHP and Mysql. This type of functionality you have seen into Wordpress Admin side if you have used Wordpress. If you have used Wordpress CMS, then at Admin side when we have create new post or page then after a specific interval of time it will save as draft our post or page automatically in Database. So our data will safe if we are forget to publish our content and we come after some time then our content will be placed in Database as draft. So, Tthis type of functionality we are going to learn into this post. In this post We will describe you a simple post example. In We have simple form for posting simple article with title and description. When user enter title and description thenafter some time interval post automatically insert into database table. This things happends only after user enter post title and description. In this tutorial if post enter for first time then it insert into database table but if post already inserted then it will update that post data on regular time interval.

Source Code


index.php


 
 <html>  
      <head>  
           <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
           <meta charset="utf-8">  
           <title>Webslesson Tutorial</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <div class="container">  
                <br />  
                <h2 align="center">Auto Save Data using Ajax, Jquery, PHP and Mysql</h2>  
                <br />  
                <div class="form-group">  
                     <label>Enter Post Title</label>  
                     <input type="text" name="post_title" id="post_title" class="form-control" />  
                </div>  
                <div class="form-group">  
                     <label>Enter Post Description</label>  
                     <textarea name="post_description" id="post_description" rows="6" class="form-control"></textarea>  
                </div>
    <div class="form-group">
     <button type="button" name="publish" class="btn btn-info">Publish</button>
    </div>
                <div class="form-group">  
                     <input type="hidden" name="post_id" id="post_id" />  
                     <div id="autoSave"></div>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      function autoSave()  
      {  
           var post_title = $('#post_title').val();  
           var post_description = $('#post_description').val();  
           var post_id = $('#post_id').val();  
           if(post_title != '' && post_description != '')  
           {  
                $.ajax({  
                     url:"save_post.php",  
                     method:"POST",  
                     data:{postTitle:post_title, postDescription:post_description, postId:post_id},  
                     dataType:"text",  
                     success:function(data)  
                     {  
                          if(data != '')  
                          {  
                               $('#post_id').val(data);  
                          }  
                          $('#autoSave').text("Post save as draft");  
                          setInterval(function(){  
                               $('#autoSave').text('');  
                          }, 5000);  
                     }  
                });  
           }            
      }  
      setInterval(function(){   
           autoSave();   
           }, 10000);  
 });  
 </script>
 

save_post.php


 
 <?php  
 $connect = mysqli_connect("localhost", "root", "", "testing");
 if(isset($_POST["postTitle"]) && isset($_POST["postDescription"]))
 {
  $post_title = mysqli_real_escape_string($connect, $_POST["postTitle"]);
  $post_description = mysqli_real_escape_string($connect, $_POST["postDescription"]);
  if($_POST["postId"] != '')  
  {  
    //update post  
    $sql = "UPDATE tbl_post SET post_title = '".$post_title."', post_description = '".$post_description."' WHERE post_id = '".$_POST["postId"]."'";  
    mysqli_query($connect, $sql);  
  }  
  else  
  {  
    //insert post  
    $sql = "INSERT INTO tbl_post(post_title, post_description, post_status) VALUES ('".$post_title."', '".$post_description."', 'draft')";  
    mysqli_query($connect, $sql);  
    echo mysqli_insert_id($connect);  
  }
 }  
 ?>
 

Database

 
 CREATE TABLE IF NOT EXISTS `tbl_post` (  
  `post_id` int(11) NOT NULL AUTO_INCREMENT,  
  `post_title` text NOT NULL,  
  `post_description` text NOT NULL,  
  `post_status` varchar(15) NOT NULL,  
  PRIMARY KEY (`post_id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
 

Friday 11 March 2016

Ajax Live Data Search using Jquery PHP MySql







In this tutorial we are going to learn Ajax Live Search with PHP and MySql with Jquery. In most of the site we can see there is one search bar on the site and we can search content of that site. If you have use Facebook or twitter there is one amazing live search functionality available for search new friends or followers. In those site suppose we enter some text for find from those site then we can get instant result from site without page refresh. This functionality is done by Ajax with Jquery. With the help of Jquery we can use Ajax http dom function, with the help of this function it search data on server side and send back result to front end webpage without page refresh. This functionality will give amazing look to your site. I have provide source code with this post. I hope you can learn this things.








Source Code


index.php


<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Webslesson Tutorial</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center">Ajax Live Data Search using Jquery PHP MySql</h2><br />
   <div class="form-group">
    <div class="input-group">
     <span class="input-group-addon">Search</span>
     <input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
    </div>
   </div>
   <br />
   <div id="result"></div>
  </div>
 </body>
</html>


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

 load_data();

 function load_data(query)
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   data:{query:query},
   success:function(data)
   {
    $('#result').html(data);
   }
  });
 }
 $('#search_text').keyup(function(){
  var search = $(this).val();
  if(search != '')
  {
   load_data(search);
  }
  else
  {
   load_data();
  }
 });
});
</script>

fetch.php


<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
if(isset($_POST["query"]))
{
 $search = mysqli_real_escape_string($connect, $_POST["query"]);
 $query = "
  SELECT * FROM tbl_customer 
  WHERE CustomerName LIKE '%".$search."%'
  OR Address LIKE '%".$search."%' 
  OR City LIKE '%".$search."%' 
  OR PostalCode LIKE '%".$search."%' 
  OR Country LIKE '%".$search."%'
 ";
}
else
{
 $query = "
  SELECT * FROM tbl_customer ORDER BY CustomerID
 ";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
 $output .= '
  <div class="table-responsive">
   <table class="table table bordered">
    <tr>
     <th>Customer Name</th>
     <th>Address</th>
     <th>City</th>
     <th>Postal Code</th>
     <th>Country</th>
    </tr>
 ';
 while($row = mysqli_fetch_array($result))
 {
  $output .= '
   <tr>
    <td>'.$row["CustomerName"].'</td>
    <td>'.$row["Address"].'</td>
    <td>'.$row["City"].'</td>
    <td>'.$row["PostalCode"].'</td>
    <td>'.$row["Country"].'</td>
   </tr>
  ';
 }
 echo $output;
}
else
{
 echo 'Data Not Found';
}

?>

--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_customer`
--

CREATE TABLE IF NOT EXISTS `tbl_customer` (
  `CustomerID` int(11) NOT NULL AUTO_INCREMENT,
  `CustomerName` varchar(250) NOT NULL,
  `Address` text NOT NULL,
  `City` varchar(250) NOT NULL,
  `PostalCode` varchar(30) NOT NULL,
  `Country` varchar(100) NOT NULL,
  PRIMARY KEY (`CustomerID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;

--
-- Dumping data for table `tbl_customer`
--

INSERT INTO `tbl_customer` (`CustomerID`, `CustomerName`, `Address`, `City`, `PostalCode`, `Country`) VALUES
(1, 'Maria Anders', 'Obere Str. 57', 'Berlin', '12209', 'Germany'),
(2, 'Ana Trujillo', 'Avda. de la Construction 2222', 'Mexico D.F.', '5021', 'Mexico'),
(3, 'Antonio Moreno', 'Mataderos 2312', 'Mexico D.F.', '5023', 'Mexico'),
(4, 'Thomas Hardy', '120 Hanover Sq.', 'London', 'WA1 1DP', 'UK'),
(5, 'Paula Parente', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(6, 'Wolski Zbyszek', 'ul. Filtrowa 68', 'Walla', '01-012', 'Poland'),
(7, 'Matti Karttunen', 'Keskuskatu 45', 'Helsinki', '21240', 'Finland'),
(8, 'Karl Jablonski', '305 - 14th Ave. S. Suite 3B', 'Seattle', '98128', 'USA'),
(9, 'Paula Parente', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(10, 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', '90110', 'Finland'),
(11, 'Paul Henriot', '2, rue du Commerce', 'Reims', '51100', 'France'),
(12, 'Helvetius Nagy', '722 DaVinci Blvd.', 'Kirkland', '98034', 'USA'),
(13, 'Karin Josephs', 'Luisenstr. 48', 'Butte', '59801', 'USA');

You can also see - Live Data Search in Codeigniter using Ajax JQuery

Thursday 10 March 2016

How to get Multiple Checkbox values in php



In this tutorial we are going to learn how to get Multiple Checkbox values in php and Insert or Add multiple checked check boxes values into Mysql Database Table by using PHP Script. This is very simple things every experienced programmer know this things but If new programmer don't know this things. This tutorial is for beginner php programmer. In php , If we want get the single value of checkbox then it simply get by post method but problem is there if we want get the values from multiple checkbox then at that time problem occur. This things is done by define multiple checkbox with same name with array and then after use foreach to fetch all values of checkbox.




Source Code


<?php

$connect = mysqli_connect("localhost", "root", "", "testing");

?>
<html>  
      <head>  
           <title>Webslesson Tutorial</title> 
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
     <style>
   
   .box
   {
    width:750px;
    padding:20px;
    background-color:#fff;
    border:1px solid #ccc;
    border-radius:5px;
    margin-top:100px;
   }
  </style>
      </head>  
      <body>  
        <div class="container box">
          <h3 align="center">Get Multiple Checkbox values and Insert into Mysql in PHP</h3><br />
          <h4>Please Select Programming Language</h4><br />  
          <form method="post">
           <p><input type="checkbox" name="language[]" value="C" /> C</p>
           <p><input type="checkbox" name="language[]" value="C++" /> C++</p>
           <p><input type="checkbox" name="language[]" value="C#" /> C#</p>
           <p><input type="checkbox" name="language[]" value="Java" /> Java</p>
           <p><input type="checkbox" name="language[]" value="PHP" /> PHP</p>
           <p><input type="submit" name="submit" class="btn btn-info" value="Submit" /></p>
          </form>
          <?php
          if(isset($_POST["submit"]))
          {
           $for_query = '';
           if(!empty($_POST["language"]))
           {
            foreach($_POST["language"] as $language)
            {
             $for_query .= $language . ', ';
            }
            $for_query = substr($for_query, 0, -2);
            $query = "INSERT INTO tbl_language (name) VALUES ('$for_query')";
            if(mysqli_query($connect, $query))
            {
             echo '<h3>You have select following language</h3>';
                echo '<label class="text-success">' . $for_query . '</label>';
            }
           }
           else
           {
            echo "<label class='text-danger'>* Please Select Atleast one Programming language</label>";
           }
          }
          ?>
     <br />
         </div>  
      </body>  
 </html>