Wednesday, 30 November 2016

PHP Ajax Crud - Insert Update Delete with Stored Procedure



If you are looking for tutorial on Stored Procedure for Crud operation in PHP with Ajax Jquery then we are going to discuss one more advance topic in web development. In this tutorial we will discuss how can we use store procedure with Ajax and Jquery for Insert Update Delete and fetch data from Mysql table in php script. In this tutorial we will make crud operation in php with ajax. For making crud operation we will use stored procedure for making crud operation in php with Ajax. In this crud operation we have use Ajax with php so all operation will be done without page refresh. Here crud means create, read, update and delete of database table data. Insert, Update, and Delete features is almost use in every website in PHP with Ajax. In this script, we will fetch users data from database and display that user data on web page with update link and delete link. By this type of link we can update and delete data from database. This operation has been done without page refresh event. For this type of operation here we will use stored procedure. First of all what is stored procedure. Stored procedure is a collection of query. It is also called pre compiled sql query. Stored Procedure is mainly used for enterprise level application. If you are working on any large data project then you can use stored procedure for Insert Update Delete of data operation. So here we will stored procedure from crud operation in php with Ajax.

This is our complete system in which we can fetch, insert, edit and delete data from database by using stored procedure in php script with Ajax request. Insert, Fetch, Update and delete records from database by using php is a very simple feature for new programmer. But here is something complex task, In this task first of all we have use stored procedure for crud operation and second is we have use ajax method with stored procedure for crud operation. So it is something new feature, if you have working on very large data application then you can use stored procedure and with Ajax request. You application working speed will be increase than normal php application. This is because stored procedure execute query at database server not on php script. So your application will execute faster than normal php application. Insert Update delete and fetch data is the normal operation in any web application. So if this operation perform fast then your application will run fast. So for execute this basic operation fast, then you can use stored procedure in your application. Mainly stored procedure are stored in your data base and it will execute from database so it will reduce execution load on your php page. So this way we can increase execution speed of any web application by using stored procedure in php script with Ajax method.

Source Code


Users


 --  
 -- Database: `crud`  
 --  
 CREATE DATABASE `crud` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;  
 USE `crud`;  
 -- --------------------------------------------------------  
 --  
 -- Table structure for table `users`  
 --  
 CREATE TABLE IF NOT EXISTS `users` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `first_name` varchar(150) NOT NULL,  
  `last_name` varchar(150) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=23 ;  
 --  
 -- Dumping data for table `users`  
 --  
 INSERT INTO `users` (`id`, `first_name`, `last_name`) VALUES  
 (17, 'Rosie', 'Peele'),  
 (18, 'Joseph', 'Harman'),  
 (19, 'John', 'Moss'),  
 (20, 'Lillie', 'Ferrari'),  
 (21, 'Yolanda', 'Green'),  
 (22, 'Cara', 'Gariepy');  

index.php


 <html>  
      <head>  
           <title>PHP Ajax Crud - Insert Update Delete with Stored Procedure</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>  
                body  
                {  
                     margin:0;  
                     padding:0;  
                     background-color:#f1f1f1;  
                }  
                .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">PHP Ajax Crud - Insert Update Delete with Stored Procedure</h3>  
                <br /><br />  
                <br /><br />  
                <label>Enter First Name</label>  
                <input type="text" name="first_name" id="first_name" class="form-control" />  
                <br />  
                <label>Enter Last Name</label>  
                <input type="text" name="last_name" id="last_name" class="form-control" />  
                <br /><br />  
                <div align="center">  
                     <input type="hidden" name="id" id="user_id" />  
                     <button type="button" name="action" id="action" class="btn btn-warning">Add</button>  
                </div>  
                <br />  
                <br />  
                <div id="result" class="table-responsive">  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      fetchUser();  
      function fetchUser()  
      {  
           var action = "select";  
           $.ajax({  
                url : "select.php",  
                method:"POST",  
                data:{action:action},  
                success:function(data){  
                     $('#first_name').val('');  
                     $('#last_name').val('');  
                     $('#action').text("Add");  
                     $('#result').html(data);  
                }  
           });  
      }  
      $('#action').click(function(){  
           var firstName = $('#first_name').val();  
           var lastName = $('#last_name').val();  
           var id = $('#user_id').val();  
           var action = $('#action').text();  
           if(firstName != '' && lastName != '')  
           {  
                $.ajax({  
                     url : "action.php",  
                     method:"POST",  
                     data:{firstName:firstName, lastName:lastName, id:id, action:action},  
                     success:function(data){  
                          alert(data);  
                          fetchUser();  
                     }  
                });  
           }  
           else  
           {  
                alert("Both Fields are Required");  
           }  
      });  
      $(document).on('click', '.update', function(){  
           var id = $(this).attr("id");  
           $.ajax({  
                url:"fetch.php",  
                method:"POST",  
                data:{id:id},  
                dataType:"json",  
                success:function(data){  
                     $('#action').text("Edit");  
                     $('#user_id').val(id);  
                     $('#first_name').val(data.first_name);  
                     $('#last_name').val(data.last_name);  
                }  
           })  
      });  
      $(document).on('click', '.delete', function(){  
           var id = $(this).attr("id");  
           if(confirm("Are you sure you want to remove this data?"))  
           {  
                var action = "Delete";  
                $.ajax({  
                     url:"action.php",  
                     method:"POST",  
                     data:{id:id, action:action},  
                     success:function(data)  
                     {  
                          fetchUser();  
                          alert(data);  
                     }  
                })  
           }  
           else  
           {  
                return false;  
           }  
      });  
 });  
 </script>  

select.php


 <?php  
 //select.php  
 $output = '';  
 $connect = mysqli_connect("localhost", "root", "", "crud");  
 if(isset($_POST["action"]))  
 {  
      $procedure = "  
      CREATE PROCEDURE selectUser()  
      BEGIN  
      SELECT * FROM users ORDER BY id DESC;  
      END;  
      ";  
      if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS selectUser"))  
      {  
           if(mysqli_query($connect, $procedure))  
           {  
                $query = "CALL selectUser()";  
                $result = mysqli_query($connect, $query);  
                $output .= '  
                     <table class="table table-bordered">  
                          <tr>  
                               <th width="35%">First Name</th>  
                               <th width="35%">Last Name</th>  
                               <th width="15%">Update</th>  
                               <th width="15%">Delete</th>  
                          </tr>  
                ';  
                if(mysqli_num_rows($result) > 0)  
                {  
                     while($row = mysqli_fetch_array($result))  
                     {  
                          $output .= '  
                               <tr>  
                                    <td>'.$row["first_name"].'</td>  
                                    <td>'.$row["last_name"].'</td>  
                                    <td><button type="button" name="update" id="'.$row["id"].'" class="update btn btn-success btn-xs">Update</button></td>  
                                    <td><button type="button" name="delete" id="'.$row["id"].'" class="delete btn btn-danger btn-xs">Delete</button></td>  
                               </tr>  
                          ';  
                     }  
                }  
                else  
                {  
                     $output .= '  
                          <tr>  
                               <td colspan="4">Data not Found</td>  
                          </tr>  
                     ';  
                }  
                $output .= '</table>';  
                echo $output;  
           }  
      }  
 }  
 ?>  

action.php


 <?php  
 //action.php  
 if(isset($_POST["action"]))  
 {  
      $output = '';  
      $connect = mysqli_connect("localhost", "root", "", "crud");  
      if($_POST["action"] =="Add")  
      {  
           $first_name = mysqli_real_escape_string($connect, $_POST["firstName"]);  
           $last_name = mysqli_real_escape_string($connect, $_POST["lastName"]);  
           $procedure = "  
                CREATE PROCEDURE insertUser(IN firstName varchar(250), lastName varchar(250))  
                BEGIN  
                INSERT INTO users(first_name, last_name) VALUES (firstName, lastName);   
                END;  
           ";  
           if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS insertUser"))  
           {  
                if(mysqli_query($connect, $procedure))  
                {  
                     $query = "CALL insertUser('".$first_name."', '".$last_name."')";  
                     mysqli_query($connect, $query);  
                     echo 'Data Inserted';  
                }  
           }  
      }  
      if($_POST["action"] == "Edit")  
      {  
           $first_name = mysqli_real_escape_string($connect, $_POST["firstName"]);  
           $last_name = mysqli_real_escape_string($connect, $_POST["lastName"]);  
           $procedure = "  
                CREATE PROCEDURE updateUser(IN user_id int(11), firstName varchar(250), lastName varchar(250))  
                BEGIN   
                UPDATE users SET first_name = firstName, last_name = lastName  
                WHERE id = user_id;  
                END;   
           ";  
           if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS updateUser"))  
           {  
                if(mysqli_query($connect, $procedure))  
                {  
                     $query = "CALL updateUser('".$_POST["id"]."', '".$first_name."', '".$last_name."')";  
                     mysqli_query($connect, $query);  
                     echo 'Data Updated';  
                }  
           }  
      }  
      if($_POST["action"] == "Delete")  
      {  
           $procedure = "  
           CREATE PROCEDURE deleteUser(IN user_id int(11))  
           BEGIN   
           DELETE FROM users WHERE id = user_id;  
           END;  
           ";  
           if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS deleteUser"))  
           {  
                if(mysqli_query($connect, $procedure))  
                {  
                     $query = "CALL deleteUser('".$_POST["id"]."')";  
                     mysqli_query($connect, $query);  
                     echo 'Data Deleted';  
                }  
           }  
      }  
 }  
 ?>  

fetch.php


 <?php  
 //fetch.php  
 $connect = mysqli_connect("localhost","root", "", "crud");  
 if(isset($_POST["id"]))  
 {  
      $output = array();  
      $procedure = "  
      CREATE PROCEDURE whereUser(IN user_id int(11))  
      BEGIN   
      SELECT * FROM users WHERE id = user_id;  
      END;   
      ";  
      if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS whereUser"))  
      {  
           if(mysqli_query($connect, $procedure))  
           {  
                $query = "CALL whereUser(".$_POST["id"].")";  
                $result = mysqli_query($connect, $query);  
                while($row = mysqli_fetch_array($result))  
                {  
                     $output['first_name'] = $row["first_name"];  
                     $output['last_name'] = $row["last_name"];  
                }  
                echo json_encode($output);  
           }  
      }  
 }  
 ?>  

Friday, 25 November 2016

Upload Multiple Images by Using PHP Ajax Jquery with Bootstrap Modal



This one more tutorial on how to use Bootstrap Modal in Web Development. In this post we will use Bootstrap Modal for upload multiple images on folder by using PHP script with Ajax Jquery without refreshing of page. In this example we will make system for uploading one or more than one image to the specified path. Here we will use Bootstrap Modal for selecting multiple images. On web page we will put simple button and when we have click on that button then after modal will popup on web page and In modal we will put input type file tag and from that tag we can select multiple images for upload. For uploading images to specified path we have use php script for uploading multiple images to specified path as back end by called by Ajax request. For this things we have create one button and then after we have create modal. By clicking on button we can pop up modal on web page. From this modal we can select multiple file and when we have select file then at that time jquery code has been execute and form has been submitted. When form submitted after we have create ajax request and by using form data object we have send selected file data with ajax request to the php script and by php script we have upload multiple images to the folder. After uploading image we have fetch all images from folder by using glob() function and then after we have display images on web page.



Source Code


index.php


 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Upload Multiple Image by Using PHP Ajax Jquery with Bootstrap Modal</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>  
           <br />  
           <div class="container">  
                <h3 align="center">Upload Multiple Image by Using PHP Ajax Jquery with Bootstrap Modal</h3><br />  
                <br />  
                <br />  
                <div align="center">  
                     <button type="button" data-toggle="modal" data-target="#uploadModal" class="btn btn-info btn-lg">Upload Images</button>  
                </div>  
                <br /><br />  
                <div id="gallery">  
                <?php  
                $images = glob("upload/*.*");  
                foreach($images as $image)  
                {  
                     echo '<div class="col-md-1" align="center" ><img src="' . $image .'" width="100px" height="100px" style="margin-top:15px; padding:8px; border:1px solid #ccc;" /></div>';  
                }  
                ?>  
                </div>  
                <br />  
                <br />  
           </div>  
           <br />  
      </body>  
 </html>  
 <div id="uploadModal" class="modal fade">  
      <div class="modal-dialog">  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">&times;</button>  
                     <h4 class="modal-title">Upload Multiple Files</h4>  
                </div>  
                <div class="modal-body">  
                     <form method="post" id="upload_form">  
                          <label>Select Multiple Image</label>  
                          <input type="file" name="images[]" id="select_image" multiple />  
                     </form>  
                </div>  
           </div>  
      </div>  
 </div>  
 <script>  
 $(document).ready(function(){  
      $('#select_image').change(function(){3  
           $('#upload_form').submit();  
      });  
      $('#upload_form').on('submit', function(e){  
           e.preventDefault();  
           $.ajax({  
                url :"upload.php",  
                method:"POST",  
                data:new FormData(this),  
                contentType:false,  
                processData:false,  
                success:function(data){  
                     $('#select_image').val('');  
                     $('#uploadModal').modal('hide');  
                     $('#gallery').html(data);  
                }  
           })  
      });  
 });  
 </script>  

upload.php


 <?php  
 //upload.php  
 $output = '';  
 if(is_array($_FILES))  
 {  
      foreach($_FILES['images']['name'] as $name => $value)  
      {  
           $file_name = explode(".", $_FILES['images']['name'][$name]);  
           $allowed_extension = array("jpg", "jpeg", "png", "gif");  
           if(in_array($file_name[1], $allowed_extension))  
           {  
                $new_name = rand() . '.'. $file_name[1];  
                $sourcePath = $_FILES["images"]["tmp_name"][$name];  
                $targetPath = "upload/".$new_name;  
                move_uploaded_file($sourcePath, $targetPath);  
           }  
      }  
      $images = glob("upload/*.*");  
      foreach($images as $image)  
      {  
           $output .= '<div class="col-md-1" align="center" ><img src="' . $image .'" width="100px" height="100px" style="margin-top:15px; padding:8px; border:1px solid #ccc;" /></div>';  
      }  
      echo $output;  
 }  
 ?>  

Thursday, 24 November 2016

Codeigniter Tutorial - Check Email availability using Ajax



This our one more tutorial in Codeigniter. In this tutorial we will discussing on how can we check email is available for registration or not by using Ajax with Jquery in Codeigniter framework. In most of the website registration we have use email for identify for login into system, then at that time we want to check particular email is already register into our system or not. So it is very important task to check email is already register or not at the time of registration. So In this video we have seen how can we validate email already registered or not in codeigniter application by using Ajax with Jquery. Here we have simple load register page from controller and then after on that view page we have write jquery code on textbox change event. So when we have enter email and go to password field then jquery code execute and in that code we have make ajax request and by using we have send request to controller and in controller first we have check email is proper or not if email is proper then it again check email is available in database or not so it go to model and in it will check email register or not and send result to controller and controller send result to view page. So This way whole cycle of codeigniter framework will run for checking email register or not by using Ajax with Jquery.



Source Code


Controller - main.php


 <?php  
 defined('BASEPATH') OR exit('No direct script access allowed');  
 class Main extends CI_Controller {  
      //functions  
      function email_availibility()  
      {  
           $data["title"] = "Codeigniter Tutorial - Check Email availibility using Ajax";  
           $this->load->view("email_availibility", $data);  
      }  
      function check_email_avalibility()  
      {  
           if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))  
           {  
                echo '<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> Invalid Email</span></label>';  
           }  
           else  
           {  
                $this->load->model("main_model");  
                if($this->main_model->is_email_available($_POST["email"]))  
                {  
                     echo '<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> Email Already register</label>';  
                }  
                else  
                {  
                     echo '<label class="text-success"><span class="glyphicon glyphicon-ok"></span> Email Available</label>';  
                }  
           }  
      }       
 }  
 ?>  

Models - main_model.php


 <?php  
 class Main_model extends CI_Model  
 {  
      function is_email_available($email)  
      {  
           $this->db->where('email', $email);  
           $query = $this->db->get("register");  
           if($query->num_rows() > 0)  
           {  
                return true;  
           }  
           else  
           {  
                return false;  
           }  
      }  
 }  
 ?>  

Views - email_availibility.php


 <!DOCTYPE html>  
 <html>  
 <head>  
      <title>Webslesson | <?php echo $title; ?></title>  
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  
 </head>  
 <body>  
      <div class="container" style="width:600px">  
           <br /><br /><br />  
           <h3><?php echo $title; ?></h3>  
           <br />  
           <label>Enter Email</label>  
           <input type="text" name="email" id="email" class="form-control" />  
           <span id="email_result"></span>  
           <br /><br />  
           <label>Enter Password</label>  
           <input type="text" name="password" id="password" class="form-control" />  
      </div>  
 </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('#email').change(function(){  
           var email = $('#email').val();  
           if(email != '')  
           {  
                $.ajax({  
                     url:"<?php echo base_url(); ?>main/check_email_avalibility",  
                     method:"POST",  
                     data:{email:email},  
                     success:function(data){  
                          $('#email_result').html(data);  
                     }  
                });  
           }  
      });  
 });  
 </script>  

Wednesday, 23 November 2016

Make accordion by using Bootstrap Collapse and Panels with PHP Script



If you want to make accordion by using large amount of dynamic data then in this post we are going to learn how to use Bootstrap Collapse with php script. By Bootstrap Collapse we will create accordion from dynamic data get from database and display on web page. By using Bootstrap Collapse we can display large amount of data on web page. We can hide content and only visible after we have click on that content. So by using Bootstrap Collapse we have create accordion and for see particular content by just click on title of that particular content. Here we will use display post title and post description and by using Bootstrap Collapse we will hide post description and only display post title. For seeing post description we have to click on post title then after we can see the post description of that post. So this way we can load large amount of content on single page by using Bootstrap Collapse. So this way we can load large amount of content on single web page in very less amount of space. In this post we have use bootstrap collapse and panels and by using both features we have make simple accordion. For making according first we have fetch data from table and then after we have print that data under panels and collapse class element. This way we have make accordion by using bootstrap collapse and panel class with php script.



Source Code


index.php


 <?php   
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 $query = "SELECT * FROM tbl_posts ORDER BY post_title ASC";  
 $result = mysqli_query($connect, $query);  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Make accordion by using Bootstrap Collapse and Panels with PHP Script</title>  
           <script src="jquery.js"></script>  
           <link rel="stylesheet" href="bootstrap.css" />  
           <script src="bootstrap.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:700px;">  
                <h3 align="center">Make accordion by using Bootstrap Collapse and Panels with PHP Script</h3><br />  
                <br />  
                <div class="panel-group" id="posts">  
                <?php  
                while($row = mysqli_fetch_array($result))  
                {  
                ?>  
                     <div class="panel panel-default">  
                          <div class="panel-heading">  
                               <h4 class="panel-title">  
                                    <a href="#<?php echo $row["post_id"]; ?>" data-toggle="collapse" data-parent="#posts"><?php echo $row["post_title"]; ?></a>  
                               </h4>  
                          </div>  
                          <div id="<?php echo $row["post_id"]; ?>" class="panel-collapse collapse">  
                               <div class="panel-body">  
                               <?php echo $row["post_desc"]; ?>  
                               </div>  
                          </div>  
                     </div>  
                <?php  
                }  
                ?>  
                </div>  
           </div>  
           <br />  
      </body>  
 </html>  

tbl_posts


 --  
 -- Table structure for table `tbl_posts`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_posts` (  
  `post_id` int(11) NOT NULL AUTO_INCREMENT,  
  `post_title` varchar(150) NOT NULL,  
  `post_desc` text NOT NULL,  
  PRIMARY KEY (`post_id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;  

Friday, 18 November 2016

PHP AJAX Jquery - Load Dynamic Content in Bootstrap Popover



In this tutorial we are going to discuss how to fetch data from mysql table and load that data into Bootstrap popover plugin by using PHP with Ajax Jquery without page refresh event. In my one of previous tutorial we have already discussing on how to fetch data from mysql table and load that data into Bootstrap Tooltip by using PHP with Ajax Jquery. First of all what is Popover, in web development popover is a same as Bootstrap tooltip javascript plugin that will pop up small amount of content will display if we have click on any html element on which we have applied popover. The main difference between tooltips and popover is that in popover we can contain much more content then tooltips. In this tutorial we can show content under popover when we have click on element then at that time one pop up message box will appear on the webpage with content, this pop up message box is a Bootstrap popover and it has been initialized by jQuery and here data is dynamic this data has been fetch from mysql table by using php script with help of jquery and Ajax. By using Ajax we can load this type of data without page refresh event. With the help of this Bootstrap popover we can display content for particular element when click on that element and by using this we can also load dynamic content into this Bootstrap popover. This type of feature will added functionality of your php application and we can see some type of dynamic data into this Bootstrap popover without opening of any web page. This way we can load dynamic mysql table content into Bootstrap popover by using php script with Jquery and Ajax. Here we have fetch mysql table data by using php script and we have execute php script by using ajax method and in jquery function we have used ajax method and by Bootstrap popover method we have called jquery function and so this way we can load dynamic html data into Bootstrap popover.



Source Code


 --  
 -- Table structure for table `tbl_employee`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_employee` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(50) NOT NULL,  
  `address` text NOT NULL,  
  `gender` varchar(10) NOT NULL,  
  `designation` varchar(100) NOT NULL,  
  `age` int(11) NOT NULL,  
  `image` varchar(100) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=187 ;  
 --  
 -- Dumping data for table `tbl_employee`  
 --  
 INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `image`) VALUES  
 (1, 'Bruce Tom', '656 Edsel Road\r\nSherman Oaks, CA 91403', 'Male', 'Driver', 36, '1.jpg'),  
 (5, 'Clara Gilliam', '63 Woodridge Lane\r\nMemphis, TN 38138', 'Female', 'Programmer', 24, '2.jpg'),  
 (6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26, '3.jpg'),  
 (7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 32, '4.jpg'),  
 (8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29, '5.jpg'),  
 (175, 'Ronald D. Colella', '1571 Bingamon Branch Road, Barrington, IL 60010', 'Male', 'Top executive', 32, '6.jpg'),  
 (174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 38, '7.jpg'),  
 (161, 'Glenda J. Stewart', '3482 Pursglove Court, Rossburg, OH 45362', 'Female', 'Cost consultant', 28, '8.jpg'),  
 (162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 64, '9.jpg'),  
 (163, 'William C. Wright', '2653 Pyramid Valley Road, Cedar Rapids, IA 52404', 'Male', 'Political geographer', 33, '10.jpg');  

index.php


 <?php  
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 $query = "SELECT * FROM tbl_employee ORDER BY id desc";  
 $result = mysqli_query($connect, $query);  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | PHP AJAX Jquery - Load Dynamic Content in Bootstrap Popover</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br /><br />  
           <div class="container" style="width:800px;">  
                <h2 align="center">PHP AJAX Jquery - Load Dynamic Content in Bootstrap Popover</h2>  
                <h3 align="center">Employee Data</h3>                 
                <br /><br />  
                <div class="table-responsive">  
                     <table class="table table-bordered">  
                          <tr>  
                               <th width="20%">ID</th>  
                               <th width="80%">Name</th>  
                          </tr>  
                          <?php  
                          while($row = mysqli_fetch_array($result))  
                          {  
                          ?>  
                          <tr>  
                               <td><?php echo $row["id"]; ?></td>  
                               <td><a href="#" class="hover" id="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></a></td>  
                          </tr>  
                          <?php  
                          }  
                          ?>  
                     </table>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
      $(document).ready(function(){  
           $('.hover').popover({  
                title:fetchData,  
                html:true,  
                placement:'right'  
           });  
           function fetchData(){  
                var fetch_data = '';  
                var element = $(this);  
                var id = element.attr("id");  
                $.ajax({  
                     url:"fetch.php",  
                     method:"POST",  
                     async:false,  
                     data:{id:id},  
                     success:function(data){  
                          fetch_data = data;  
                     }  
                });  
                return fetch_data;  
           }  
      });  
 </script>  

fetch.php


 <?php  
 //fetch.php  
 if(isset($_POST["id"]))  
 {  
      $output = '';  
      $connect = mysqli_connect("localhost", "root", "", "testing");  
      $query = "SELECT * FROM tbl_employee WHERE id='".$_POST["id"]."'";  
      $result = mysqli_query($connect, $query);  
      while($row = mysqli_fetch_array($result))  
      {  
           $output = '  
                <p><img src="images/'.$row["image"].'" class="img-responsive img-thumbnail" /></p>  
                <p><label>Name : '.$row['name'].'</label></p>  
                <p><label>Address : </label><br />'.$row['address'].'</p>  
                <p><label>Gender : </label>'.$row['gender'].'</p>  
                <p><label>Designation : </label>'.$row['designation'].'</p>  
                <p><label>Age : </label>'.$row['age'].' Years</p>  
           ';  
      }  
      echo $output;  
 }  
 ?>  

Thursday, 17 November 2016

PHP Login Registration Script by using password_hash() method





If you looking for how to use password_hash() method for login and registration in php script. In this tutorial we will discuss how to use php password hash method for secured login and registration. This PHP password_hash() method will creates new password hash by using effective one way hashing algorithm. This method first introduce under php 5.5 version and it will creates new password hash with 60 characters long and we will store that hashed password into our database and it is very difficult to hacked and it can be verify by using password verify method. If you are build any application and you want to implement strong login for your application then you can use this password_hash() method for strong login registration for your application. When we will register into this type of registration then password will be hashed by password_hash() method and store into database and while we will login into system then this type of hashed password can be verify by using password_verify() method. So this is the complete register login logout system by using password_hash() method. Here when new user come for register to this type of system then this system will generate hashed password from password which he has enter while registration by using password_hash() method. This method will generate 60 character long hashed password by using password hash algorithm and then after we have store that hashed password in database and when user come for login then at that user enter his password then after we have validate that user enter password with hashed password by using password_verify() method, this method verify hashed password with normal string password and if both password match then it will return true that means password match but suppose this method return false that means password not match. This is the best method for prevent from password hacking.


Source Code


index.php


 <?php  
 $connect = mysqli_connect("localhost", "root", "", "test");  
 session_start();  
 if(isset($_SESSION["username"]))  
 {  
      header("location:entry.php");  
 }  
 if(isset($_POST["register"]))  
 {  
      if(empty($_POST["username"]) || empty($_POST["password"]))  
      {  
           echo '<script>alert("Both Fields are required")</script>';  
      }  
      else  
      {  
           $username = mysqli_real_escape_string($connect, $_POST["username"]);  
           $password = mysqli_real_escape_string($connect, $_POST["password"]);  
           $password = password_hash($password, PASSWORD_DEFAULT);  
           $query = "INSERT INTO users(username, password) VALUES('$username', '$password')";  
           if(mysqli_query($connect, $query))  
           {  
                echo '<script>alert("Registration Done")</script>';  
           }  
      }  
 }  
 if(isset($_POST["login"]))  
 {  
      if(empty($_POST["username"]) || empty($_POST["password"]))  
      {  
           echo '<script>alert("Both Fields are required")</script>';  
      }  
      else  
      {  
           $username = mysqli_real_escape_string($connect, $_POST["username"]);  
           $password = mysqli_real_escape_string($connect, $_POST["password"]);  
           $query = "SELECT * FROM users WHERE username = '$username'";  
           $result = mysqli_query($connect, $query);  
           if(mysqli_num_rows($result) > 0)  
           {  
                while($row = mysqli_fetch_array($result))  
                {  
                     if(password_verify($password, $row["password"]))  
                     {  
                          //return true;  
                          $_SESSION["username"] = $username;  
                          header("location:entry.php");  
                     }  
                     else  
                     {  
                          //return false;  
                          echo '<script>alert("Wrong User Details")</script>';  
                     }  
                }  
           }  
           else  
           {  
                echo '<script>alert("Wrong User Details")</script>';  
           }  
      }  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | PHP Login Registration Script by using password_hash() method</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>  
           <br /><br />  
           <div class="container" style="width:500px;">  
                <h3 align="center">PHP Login Registration Script by using password_hash() method</h3>  
                <br />  
                <?php  
                if(isset($_GET["action"]) == "login")  
                {  
                ?>  
                <h3 align="center">Login</h3>  
                <br />  
                <form method="post">  
                     <label>Enter Username</label>  
                     <input type="text" name="username" class="form-control" />  
                     <br />  
                     <label>Enter Password</label>  
                     <input type="text" name="password" class="form-control" />  
                     <br />  
                     <input type="submit" name="login" value="Login" class="btn btn-info" />  
                     <br />  
                     <p align="center"><a href="index.php">Register</a></p>  
                </form>  
                <?php       
                }  
                else  
                {  
                ?>  
                <h3 align="center">Register</h3>  
                <br />  
                <form method="post">  
                     <label>Enter Username</label>  
                     <input type="text" name="username" class="form-control" />  
                     <br />  
                     <label>Enter Password</label>  
                     <input type="text" name="password" class="form-control" />  
                     <br />  
                     <input type="submit" name="register" value="Register" class="btn btn-info" />  
                     <br />  
                     <p align="center"><a href="index.php?action=login">Login</a></p>  
                </form>  
                <?php  
                }  
                ?>  
           </div>  
      </body>  
 </html>  

entry.php


 <?php  
 //entry.php  
 session_start();  
 if(!isset($_SESSION["username"]))  
 {  
      header("location:index.php?action=login");  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | PHP Login Registration Script by using password_hash() method</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>  
           <br /><br />  
           <div class="container" style="width:500px;">  
                <h3 align="center">PHP Login Registration Script by using password_hash() method</h3>  
                <br />  
                <?php  
                echo '<h1>Welcome - '.$_SESSION["username"].'</h1>';  
                echo '<label><a href="logout.php">Logout</a></label>';  
                ?>  
           </div>  
      </body>  
 </html>  

logout.php


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

Tuesday, 15 November 2016

Make Login Form by Using Bootstrap Collapse with PHP Ajax Jquery



If you are looking for different type of login form for your website, so here we will make login form by using Bootstrap Collapse with PHP Ajax Jquery. When you click on button then at that time login form will be visible on web page. First of all what is Bootstrap Collapse. Bootstrap Collapse is very useful in web development, by using Bootstrap Collapse can show and hide many large amount of content on web page. So here we will make login form under Bootstrap Collapse so login form will not be show on web page but it will be visible after click on button then after it will visible on webpage after this we can fill form and we can logged into site. First we have create one button and then after we have define one division tag for Bootstrap Collapse, by using Bootstrap Collapse that element will be hide and it will be display after clicking on button. So Under this Bootstrap Collapse division tag we have define login form and then after we have write jquery code on login button click event and then after we have send request to php script for verifying user login information by using Ajax method. After validate user information server will send back data to ajax request. This we have validate user login information. When user enter right data then he can be logged into system and then after he can see the logout link also and by click on logout link he can be logout from system. For logout we have also use jquery Ajax code.




Source Code


index.php


 <?php   
 session_start();  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Make Login Form by Using Bootstrap Collapse with PHP Ajax Jquery</title>  
           <script src="jquery.js"></script>  
           <link rel="stylesheet" href="bootstrap.css" />  
           <script src="bootstrap.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:700px;">  
                <h3 align="center">Make Login Form by Using Bootstrap Collapse with PHP Ajax Jquery</h3><br />  
                <br />  
                <br />  
                <br />  
                <br />  
                <br />  
                <?php  
                if(isset($_SESSION["username"]))  
                {  
                ?>  
                <div align="center">  
                     <h1>Welcome - <?php echo $_SESSION['username']; ?></h1><br />  
                     <a href="#" id="logout">Logout</a>  
                </div>  
                <?php  
                }  
                else  
                {  
                ?>  
                <div align="center">  
                     <button type="button" name="login" id="login" class="btn btn-success" data-toggle="collapse" data-target="#login_collapse">Login</button>  
                     <div id="login_collapse" class="collapse col-md-12" style="border:1px solid #ccc; background-color:#f1f1f1; margin-top:16px;">  
                          <h3 align="center">Login</h3>  
                          <label>Username</label>  
                          <input type="text" name="username" id="username" class="form-control" />  
                          <br />  
                          <label>Password</label>  
                          <input type="password" name="password" id="password" class="form-control" />  
                          <br />  
                          <button type="button" name="login_button" id="login_button" class="btn btn-warning">Login</button>  
                          <br /><br />  
                     </div>  
                </div>  
                <?php  
                }  
                ?>  
           </div>  
           <br />  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('#login_button').click(function(){  
           var username = $('#username').val();  
           var password = $('#password').val();  
           if(username != '' && password != '')  
           {  
                $.ajax({  
                     url:"action.php",  
                     method:"POST",  
                     data:{username:username, password:password},  
                     success:function(data){  
                          if(data == 'No')  
                          {  
                               alert("Wrong Data");  
                          }  
                          else  
                          {  
                               location.reload();  
                          }  
                     }  
                });  
           }  
           else  
           {  
                alert("Both Fields are required");  
           }  
      });  
      $('#logout').click(function(){  
           var action = "logout";  
           $.ajax({  
                url:"action.php",  
                method:"POST",  
                data:{action:action},  
                success:function()  
                {  
                     location.reload();  
                }  
           });  
      });  
 });  
 </script>  

action.php


 <?php  
 //action.php  
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 if(isset($_POST["username"]))  
 {  
      $username = mysqli_real_escape_string($connect, $_POST["username"]);  
      $password = mysqli_real_escape_string($connect, $_POST["password"]);  
      $query = "  
      SELECT * FROM admin_login  
      WHERE admin_name = '".$username."'  
      AND admin_password = '".$password."'  
      ";  
      $result = mysqli_query($connect, $query);  
      if(mysqli_num_rows($result) > 0)  
      {  
           $_SESSION["username"] = $username;  
           echo 'Yes';  
      }  
      else  
      {  
           echo 'No';  
      }  
 }  
 if(isset($_POST["action"]))  
 {  
      unset($_SESSION["username"]);  
 }  
 ?>  

Sunday, 13 November 2016

Make Login Form by Using Bootstrap Modal with PHP Ajax Jquery



If you are looking for something new login form style so in this post we will discussing on how can we use Bootstrap Modal for making login page in php script with Ajax Jquery. We have already developed login script with simple php code on single page. But here we will use Bootstrap Modal for developing login form. Bootstrap Modal modal is a dialog box or popup window that will be displayed on top of the web page. In web development many web site use this type of login system for their web application access. When we have click on any link or button then after Modal window will be pop up on web page and under that dialog box we will put login page so we can enter their username and password and they can access web page. First we have create Bootstrap modal by using Bootstrap css and javascript and under this modal we have create login form, after this we have create one button when we have click on that button then modal has been popup on screen with login form and when we have fill login form and click on login button then it send request to jquery code and that jquery send request to php script via ajax request and in php script we have validate user data and send back request to ajax function. This way we can login into system and by using session variable we can display username on the page if user is logged into the system and for logout we have also use ajax jquery code.


Source Code


index.php


 <?php   
 session_start();  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Make Login Form by Using Bootstrap Modal with PHP Ajax Jquery</title>  
           <script src="jquery.js"></script>  
           <link rel="stylesheet" href="bootstrap.css" />  
           <script src="bootstrap.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:700px;">  
                <h3 align="center">Make Login Form by Using Bootstrap Modal with PHP Ajax Jquery</h3><br />  
                <br />  
                <br />  
                <br />  
                <br />  
                <br />  
                <?php  
                if(isset($_SESSION['username']))  
                {  
                ?>  
                <div align="center">  
                     <h1>Welcome - <?php echo $_SESSION['username']; ?></h1><br />  
                     <a href="#" id="logout">Logout</a>  
                </div>  
                <?php  
                }  
                else  
                {  
                ?>  
                <div align="center">  
                     <button type="button" name="login" id="login" class="btn btn-success" data-toggle="modal" data-target="#loginModal">Login</button>  
                </div>  
                <?php  
                }  
                ?>  
           </div>  
           <br />  
      </body>  
 </html>  
 <div id="loginModal" class="modal fade" role="dialog">  
      <div class="modal-dialog">  
   <!-- Modal content-->  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">&times;</button>  
                     <h4 class="modal-title">Login</h4>  
                </div>  
                <div class="modal-body">  
                     <label>Username</label>  
                     <input type="text" name="username" id="username" class="form-control" />  
                     <br />  
                     <label>Password</label>  
                     <input type="password" name="password" id="password" class="form-control" />  
                     <br />  
                     <button type="button" name="login_button" id="login_button" class="btn btn-warning">Login</button>  
                </div>  
           </div>  
      </div>  
 </div>  
 <script>  
 $(document).ready(function(){  
      $('#login_button').click(function(){  
           var username = $('#username').val();  
           var password = $('#password').val();  
           if(username != '' && password != '')  
           {  
                $.ajax({  
                     url:"action.php",  
                     method:"POST",  
                     data: {username:username, password:password},  
                     success:function(data)  
                     {  
                          //alert(data);  
                          if(data == 'No')  
                          {  
                               alert("Wrong Data");  
                          }  
                          else  
                          {  
                               $('#loginModal').hide();  
                               location.reload();  
                          }  
                     }  
                });  
           }  
           else  
           {  
                alert("Both Fields are required");  
           }  
      });  
      $('#logout').click(function(){  
           var action = "logout";  
           $.ajax({  
                url:"action.php",  
                method:"POST",  
                data:{action:action},  
                success:function()  
                {  
                     location.reload();  
                }  
           });  
      });  
 });  
 </script>  

action.php


 <?php  
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 if(isset($_POST["username"]))  
 {  
      $query = "  
      SELECT * FROM admin_login  
      WHERE admin_name = '".$_POST["username"]."'  
      AND admin_password = '".$_POST["password"]."'  
      ";  
      $result = mysqli_query($connect, $query);  
      if(mysqli_num_rows($result) > 0)  
      {  
           $_SESSION['username'] = $_POST['username'];  
           echo 'Yes';  
      }  
      else  
      {  
           echo 'No';  
      }  
 }  
 if(isset($_POST["action"]))  
 {  
      unset($_SESSION["username"]);  
 }  
 ?>  

admin_login


 --  
 -- Table structure for table `admin_login`  
 --  
 CREATE TABLE IF NOT EXISTS `admin_login` (  
  `admin_id` int(11) NOT NULL AUTO_INCREMENT,  
  `admin_name` varchar(250) NOT NULL,  
  `admin_password` varchar(250) NOT NULL,  
  PRIMARY KEY (`admin_id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;  
 --  
 -- Dumping data for table `admin_login`  
 --  
 INSERT INTO `admin_login` (`admin_id`, `admin_name`, `admin_password`) VALUES  
 (1, 'admin', 'admin');  

Wednesday, 9 November 2016

Multi Tab Shopping Cart By Using PHP Ajax Jquery Bootstrap Mysql



If you are looking for PHP Ajax Jquery Shopping Cart with Bootstrap, So in this post we have discuss how make Multi Tab Shopping Cart By using PHP with Ajax Jquery. In previous one of my post on shopping cart we have make simple shopping by using session and second in second post we have develop shopping cart by drag and drop event but in this tutorial we will build multi tab shopping cart by using php script with mysql database and in this video we will use ajax method with jquery so we will add product into cart without page refresh event. For making multi tab we will use Bootstrap framework for this. This way we will developed shopping cart with multi tab by using Bootstrap with Ajax Jquery php and mysql, in one tab we will add product into cart and in second tab we will display order table with product. In this shopping cart we have first make tab for display list of product in one tab and shopping cart details in second tab. For making tab we have use bootstrap framework. After making tab we have load product details from database under product. With product we have also add on add to cart button, for add product into cart we have use jquery with ajax method, by using ajax request we can add product into cart without page refresh and product has been added into cart. For check shopping cart we have click on cart tab and under this tab we can see product details which we have added into cart in table format. We can also remove product from cart also, for removing product from cart also we have use jquery with ajax method, so we can remove product from cart without refresh. In this shopping cart we have create one session variable and we have store all details in that session variable, so we have store all product data on web page when we have put order then after that data will added into the cart.



Source Code


multi_tab_shopping_cart.php



<?php   
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "test");  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Multi Tab Shopping Cart By Using PHP Ajax Jquery Bootstrap Mysql</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>  
           <br />  
           <div class="container" style="width:800px;">  
                <h3 align="center">Multi Tab Shopping Cart By Using PHP Ajax Jquery Bootstrap Mysql</h3><br />  
                <ul class="nav nav-tabs">  
                     <li class="active"><a data-toggle="tab" href="#products">Product</a></li>  
                     <li><a data-toggle="tab" href="#cart">Cart <span class="badge"><?php if(isset($_SESSION["shopping_cart"])) { echo count($_SESSION["shopping_cart"]); } else { echo '0';}?></span></a></li>  
                </ul>  
                <div class="tab-content">  
                     <div id="products" class="tab-pane fade in active">  
                     <?php  
                     $query = "SELECT * FROM tbl_product ORDER BY id ASC";  
                     $result = mysqli_query($connect, $query);  
                     while($row = mysqli_fetch_array($result))  
                     {  
                     ?>  
                     <div class="col-md-4" style="margin-top:12px;">  
                          <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">  
                               <img src="images/<?php echo $row["image"]; ?>" class="img-responsive" /><br />  
                               <h4 class="text-info"><?php echo $row["name"]; ?></h4>  
                               <h4 class="text-danger">$ <?php echo $row["price"]; ?></h4>  
                               <input type="text" name="quantity" id="quantity<?php echo $row["id"]; ?>" class="form-control" value="1" />  
                               <input type="hidden" name="hidden_name" id="name<?php echo $row["id"]; ?>" value="<?php echo $row["name"]; ?>" />  
                               <input type="hidden" name="hidden_price" id="price<?php echo $row["id"]; ?>" value="<?php echo $row["price"]; ?>" />  
                               <input type="button" name="add_to_cart" id="<?php echo $row["id"]; ?>" style="margin-top:5px;" class="btn btn-warning form-control add_to_cart" value="Add to Cart" />  
                          </div>  
                     </div>  
                     <?php  
                     }  
                     ?>  
                     </div>  <div id="cart" class="tab-pane fade">  
                          <div class="table-responsive" id="order_table">  
                               <table class="table table-bordered">  
                                    <tr>  
                                         <th width="40%">Product Name</th>  
                                         <th width="10%">Quantity</th>  
                                         <th width="20%">Price</th>  
                                         <th width="15%">Total</th>  
                                         <th width="5%">Action</th>  
                                    </tr>  
                                    <?php  
                                    if(!empty($_SESSION["shopping_cart"]))  
                                    {  
                                         $total = 0;  
                                         foreach($_SESSION["shopping_cart"] as $keys => $values)  
                                         {                                               
                                    ?>  
                                    <tr>  
                                         <td><?php echo $values["product_name"]; ?></td>  
                                         <td><input type="text" name="quantity[]" id="quantity<?php echo $values["product_id"]; ?>" value="<?php echo $values["product_quantity"]; ?>" data-product_id="<?php echo $values["product_id"]; ?>" class="form-control quantity" /></td>  
                                         <td align="right">$ <?php echo $values["product_price"]; ?></td>  
                                         <td align="right">$ <?php echo number_format($values["product_quantity"] * $values["product_price"], 2); ?></td>  
                                         <td><button name="delete" class="btn btn-danger btn-xs delete" id="<?php echo $values["product_id"]; ?>">Remove</button></td>  
                                    </tr>  
                                    <?php  
                                              $total = $total + ($values["product_quantity"] * $values["product_price"]);  
                                         }  
                                    ?>  
                                    <tr>  
                                         <td colspan="3" align="right">Total</td>  
                                         <td align="right">$ <?php echo number_format($total, 2); ?></td>  
                                         <td></td>  
                                    </tr>  
                                    <tr>  
                                         <td colspan="5" align="center">  
                                              <form method="post" action="cart.php">  
                                                   <input type="submit" name="place_order" class="btn btn-warning" value="Place Order" />  
                                              </form>  
                                         </td>  
                                    </tr>  
                                    <?php  
                                    }  
                                    ?>  
                               </table>  
                          </div>  
                     </div>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(data){  
      $('.add_to_cart').click(function(){  
           var product_id = $(this).attr("id");  
           var product_name = $('#name'+product_id).val();  
           var product_price = $('#price'+product_id).val();  
           var product_quantity = $('#quantity'+product_id).val();  
           var action = "add";  
           if(product_quantity > 0)  
           {  
                $.ajax({  
                     url:"action.php",  
                     method:"POST",  
                     dataType:"json",  
                     data:{  
                          product_id:product_id,   
                          product_name:product_name,   
                          product_price:product_price,   
                          product_quantity:product_quantity,   
                          action:action  
                     },  
                     success:function(data)  
                     {  
                          $('#order_table').html(data.order_table);  
                          $('.badge').text(data.cart_item);  
                          alert("Product has been Added into Cart");  
                     }  
                });  
           }  
           else  
           {  
                alert("Please Enter Number of Quantity")  
           }  
      });  
      $(document).on('click', '.delete', function(){  
           var product_id = $(this).attr("id");  
           var action = "remove";  
           if(confirm("Are you sure you want to remove this product?"))  
           {  
                $.ajax({  
                     url:"action.php",  
                     method:"POST",  
                     dataType:"json",  
                     data:{product_id:product_id, action:action},  
                     success:function(data){  
                          $('#order_table').html(data.order_table);  
                          $('.badge').text(data.cart_item);  
                     }  
                });  
           }  
           else  
           {  
                return false;  
           }  
      });  
      $(document).on('keyup', '.quantity', function(){  
           var product_id = $(this).data("product_id");  
           var quantity = $(this).val();  
           var action = "quantity_change";  
           if(quantity != '')  
           {  
                $.ajax({  
                     url :"action.php",  
                     method:"POST",  
                     dataType:"json",  
                     data:{product_id:product_id, quantity:quantity, action:action},  
                     success:function(data){  
                          $('#order_table').html(data.order_table);  
                     }  
                });  
           }  
      });  
 });  
 </script>



action.php



<?php  
 //action.php  
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "test");  
 if(isset($_POST["product_id"]))  
 {  
      $order_table = '';  
      $message = '';  
      if($_POST["action"] == "add")  
      {  
           if(isset($_SESSION["shopping_cart"]))  
           {  
                $is_available = 0;  
                foreach($_SESSION["shopping_cart"] as $keys => $values)  
                {  
                     if($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"])  
                     {  
                          $is_available++;  
                          $_SESSION["shopping_cart"][$keys]['product_quantity'] = $_SESSION["shopping_cart"][$keys]['product_quantity'] + $_POST["product_quantity"];  
                     }  
                }  
                if($is_available < 1)  
                {  
                     $item_array = array(  
                          'product_id'               =>     $_POST["product_id"],  
                          'product_name'               =>     $_POST["product_name"],  
                          'product_price'               =>     $_POST["product_price"],  
                          'product_quantity'          =>     $_POST["product_quantity"]  
                     );  
                     $_SESSION["shopping_cart"][] = $item_array;  
                }  
           }  
           else  
           {  
                $item_array = array(  
                     'product_id'               =>     $_POST["product_id"],  
                     'product_name'               =>     $_POST["product_name"],  
                     'product_price'               =>     $_POST["product_price"],  
                     'product_quantity'          =>     $_POST["product_quantity"]  
                );  
                $_SESSION["shopping_cart"][] = $item_array;  
           }  
      }  
      if($_POST["action"] == "remove")  
      {  
           foreach($_SESSION["shopping_cart"] as $keys => $values)  
           {  
                if($values["product_id"] == $_POST["product_id"])  
                {  
                     unset($_SESSION["shopping_cart"][$keys]);  
                     $message = '<label class="text-success">Product Removed</label>';  
                }  
           }  
      }  
      if($_POST["action"] == "quantity_change")  
      {  
           foreach($_SESSION["shopping_cart"] as $keys => $values)  
           {  
                if($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"])  
                {  
                     $_SESSION["shopping_cart"][$keys]['product_quantity'] = $_POST["quantity"];  
                }  
           }  
      }  
      $order_table .= '  
           '.$message.'  
           <table class="table table-bordered">  
                <tr>  
                     <th width="40%">Product Name</th>  
                     <th width="10%">Quantity</th>  
                     <th width="20%">Price</th>  
                     <th width="15%">Total</th>  
                     <th width="5%">Action</th>  
                </tr>  
           ';  
      if(!empty($_SESSION["shopping_cart"]))  
      {  
           $total = 0;  
           foreach($_SESSION["shopping_cart"] as $keys => $values)  
           {  
                $order_table .= '  
                     <tr>  
                          <td>'.$values["product_name"].'</td>  
                          <td><input type="text" name="quantity[]" id="quantity'.$values["product_id"].'" value="'.$values["product_quantity"].'" class="form-control quantity" data-product_id="'.$values["product_id"].'" /></td>  
                          <td align="right">$ '.$values["product_price"].'</td>  
                          <td align="right">$ '.number_format($values["product_quantity"] * $values["product_price"], 2).'</td>  
                          <td><button name="delete" class="btn btn-danger btn-xs delete" id="'.$values["product_id"].'">Remove</button></td>  
                     </tr>  
                ';  
                $total = $total + ($values["product_quantity"] * $values["product_price"]);  
           }  
           $order_table .= '  
                <tr>  
                     <td colspan="3" align="right">Total</td>  
                     <td align="right">$ '.number_format($total, 2).'</td>  
                     <td></td>  
                </tr>  
                <tr>  
                     <td colspan="5" align="center">  
                          <form method="post" action="cart.php">  
                               <input type="submit" name="place_order" class="btn btn-warning" value="Place Order" />  
                          </form>  
                     </td>  
                </tr>  
           ';  
      }  
      $order_table .= '</table>';  
      $output = array(  
           'order_table'     =>     $order_table,  
           'cart_item'          =>     count($_SESSION["shopping_cart"])  
      );  
      echo json_encode($output);  
 }  
 ?>


cart.php



<?php  
 //cart.php  
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "shopping_cart");  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Multi Tab Shopping Cart By Using PHP Ajax Jquery Bootstrap Mysql</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>  
           <br />  
           <div class="container" style="width:800px;">  
                <?php  
                if(isset($_POST["place_order"]))  
                {  
                     $insert_order = "  
                     INSERT INTO tbl_order(customer_id, creation_date, order_status)  
                     VALUES('1', '".date('Y-m-d')."', 'pending')  
                     ";  
                     $order_id = "";  
                     if(mysqli_query($connect, $insert_order))  
                     {  
                          $order_id = mysqli_insert_id($connect);  
                     }  
                     $_SESSION["order_id"] = $order_id;  
                     $order_details = "";  
                     foreach($_SESSION["shopping_cart"] as $keys => $values)  
                     {  
                          $order_details .= "  
                          INSERT INTO tbl_order_details(order_id, product_name, product_price, product_quantity)  
                          VALUES('".$order_id."', '".$values["product_name"]."', '".$values["product_price"]."', '".$values["product_quantity"]."');  
                          ";  
                     }  
                     if(mysqli_multi_query($connect, $order_details))  
                     {  
                          unset($_SESSION["shopping_cart"]);  
                          echo '<script>alert("You have successfully place an order...Thank you")</script>';  
                          echo '<script>window.location.href="cart.php"</script>';  
                     }  
                }  
                if(isset($_SESSION["order_id"]))  
                {  
                     $customer_details = '';  
                     $order_details = '';  
                     $total = 0;  
                     $query = '  
                     SELECT * FROM tbl_order  
                     INNER JOIN tbl_order_details  
                     ON tbl_order_details.order_id = tbl_order.order_id  
                     INNER JOIN tbl_customer  
                     ON tbl_customer.CustomerID = tbl_order.customer_id  
                     WHERE tbl_order.order_id = "'.$_SESSION["order_id"].'"  
                     ';  
                     $result = mysqli_query($connect, $query);  
                     while($row = mysqli_fetch_array($result))  
                     {  
                          $customer_details = '  
                          <label>'.$row["CustomerName"].'</label>  
                          <p>'.$row["Address"].'</p>  
                          <p>'.$row["City"].', '.$row["PostalCode"].'</p>  
                          <p>'.$row["Country"].'</p>  
                          ';  
                          $order_details .= "  
                               <tr>  
                                    <td>".$row["product_name"]."</td>  
                                    <td>".$row["product_quantity"]."</td>  
                                    <td>".$row["product_price"]."</td>  
                                    <td>".number_format($row["product_quantity"] * $row["product_price"], 2)."</td>  
                               </tr>  
                          ";  
                          $total = $total + ($row["product_quantity"] * $row["product_price"]);  
                     }  
                     echo '  
                     <h3 align="center">Order Summary for Order No.'.$_SESSION["order_id"].'</h3>  
                     <div class="table-responsive">  
                          <table class="table">  
                               <tr>  
                                    <td><label>Customer Details</label></td>  
                               </tr>  
                               <tr>  
                                    <td>'.$customer_details.'</td>  
                               </tr>  
                               <tr>  
                                    <td><label>Order Details</label></td>  
                               </tr>  
                               <tr>  
                                    <td>  
                                         <table class="table table-bordered">  
                                              <tr>  
                                                   <th width="50%">Product Name</th>  
                                                   <th width="15%">Quantity</th>  
                                                   <th width="15%">Price</th>  
                                                   <th width="20%">Total</th>  
                                              </tr>  
                                              '.$order_details.'  
                                              <tr>  
                                                   <td colspan="3" align="right"><label>Total</label></td>  
                                                   <td>'.number_format($total, 2).'</td>  
                                              </tr>  
                                         </table>  
                                    </td>  
                               </tr>  
                          </table>  
                     </div>  
                     ';  
                }  
                ?>  
           </div>  
      </body>  
 </html> 

Sunday, 6 November 2016

CodeIgniter Tutorial - Compress and Resize Uploaded Image



Hello friends in previous post on codeigniter tutorial, we have discuss on how to upload image using ajax with jquery in Codeigniter application. Now in this post we will discuss how to compress image and how to resize uploaded image and display that image on web page without page refresh. In this post we have first load image library GD2 with predefine option. Method of This image library will compress and resize uploaded image and store into upload folder. Then after we have store image name under database and then after we have fetch image name from database and display all images on web page after successfully image uploaded with out page refresh. This way we have make simple image gallery in codeigniter framework, in this gallery we have compress and resize uploaded image without page refresh using ajax request. So this is my tutorial on how to compress and resize uploaded image in Codeigniter framework.



Source Code


Controllers - main.php


 function image_upload()  
      {  
           $data['title'] = "Upload Image using Ajax JQuery in CodeIgniter";  
           $this->load->model('main_model');  
           $data["image_data"] = $this->main_model->fetch_image();  
           $this->load->view('image_upload', $data);  
      }  
      function ajax_upload()  
      {  
           if(isset($_FILES["image_file"]["name"]))  
           {  
                $config['upload_path'] = './upload/';  
                $config['allowed_types'] = 'jpg|jpeg|png|gif';  
                $this->load->library('upload', $config);  
                if(!$this->upload->do_upload('image_file'))  
                {  
                     echo $this->upload->display_errors();  
                }  
                else  
                {  
                     $data = $this->upload->data();  
                     $config['image_library'] = 'gd2';  
                     $config['source_image'] = './upload/'.$data["file_name"];  
                     $config['create_thumb'] = FALSE;  
                     $config['maintain_ratio'] = FALSE;  
                     $config['quality'] = '60%';  
                     $config['width'] = 200;  
                     $config['height'] = 200;  
                     $config['new_image'] = './upload/'.$data["file_name"];  
                     $this->load->library('image_lib', $config);  
                     $this->image_lib->resize();  
                     $this->load->model('main_model');  
                     $image_data = array(  
                          'name'          =>     $data["file_name"]  
                          );  
                     $this->main_model->insert_image($image_data);  
                     echo $this->main_model->fetch_image();  
                     //echo '<img src="'.base_url().'upload/'.$data["file_name"].'" width="300" height="225" class="img-thumbnail" />';  
                }  
           }  
      }  

Models - main_model.php


 function insert_image($data)  
      {  
           $this->db->insert("tbl_images", $data);  
      }  
      function fetch_image()  
      {  
           $output = '';  
           $this->db->select("name");  
           $this->db->from("tbl_images");  
           $this->db->order_by("id", "DESC");  
           $query = $this->db->get();  
           foreach($query->result() as $row)  
           {  
                $output .= '  
                     <div class="col-md-3">  
                          <img src="'.base_url().'upload/'.$row->name.'" class="img-responsive img-thumbnail" />  
                     </div>  
                ';  
           }  
           return $output;  
      }  

Views - image_upload.php


 <!DOCTYPE html>  
 <html>  
 <head>  
      <title>Webslesson | <?php echo $title; ?></title>  
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  
 </head>  
 <body>  
      <div class="container">  
           <br /><br /><br />  
           <h3 align="center"><?php echo $title; ?></h3>  
           <form method="post" id="upload_form" align="center" enctype="multipart/form-data">  
                <input type="file" name="image_file" id="image_file" />  
                <br />  
                <br />  
                <input type="submit" name="upload" id="upload" value="Upload" class="btn btn-info" />  
           </form>  
           <br />  
           <br />  
           <div id="uploaded_image">  
           <?php echo $image_data; ?>  
           </div>  
      </div>  
 </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('#upload_form').on('submit', function(e){  
           e.preventDefault();  
           if($('#image_file').val() == '')  
           {  
                alert("Please Select the File");  
           }  
           else  
           {  
                $.ajax({  
                     url:"<?php echo base_url(); ?>main/ajax_upload",   
                     //base_url() = http://localhost/tutorial/codeigniter  
                     method:"POST",  
                     data:new FormData(this),  
                     contentType: false,  
                     cache: false,  
                     processData:false,  
                     success:function(data)  
                     {  
                          $('#uploaded_image').html(data);  
                     }  
                });  
           }  
      });  
 });  
 </script>  

tbl_images


 --  
 -- Table structure for table `tbl_images`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_images` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(255) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;  
 --  
 -- Dumping data for table `tbl_images`  
 --