Wednesday, 14 November 2018

How to Store Multiple Images in Database using PHP Ajax



In Web development file or image upload is a very required feature. There are many ways we can store images. One we can upload image on server and store image name in Mysql database using PHP. In another way we can directly store images in Mysql database table using PHP also. There are many post we have publish on upload single image or multiple images on server and store image details in database using PHP. But in this post we have convered one advance topic like how to insert multiple image in mysql database using PHP with Ajax.

In one of our previous post we have step by step describe how to insert and fetch images from Mysql database using PHP. But in that post we have use only PHP script for insert image into mysql database and then after fetch images from Mysql database and display on web page using PHP. But here we have make one form with option like select multiple images at the same time and by using jQuery Ajax send that images data to PHP. In PHP script it will convert image into binary string format and insert into Mysql database one by one. After inserting multiple images into Mysql database, now we want to retrieve images from mysql database and display on web page. For this also we have use jQuery and Ajax function which send request to PHP, at PHP script that fetch data from mysql table and convert that data into html format and send back to ajax request. Now we have discuss source of How to Upload Multiple Images in Database using PHP Ajax.








Mysql Database


Run following SQL script into your phpMyadmin, this script will make tbl_images table into your database.


--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_images`
--

CREATE TABLE `tbl_images` (
  `image_id` int(11) NOT NULL,
  `images` longblob NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_images`
--
ALTER TABLE `tbl_images`
  ADD PRIMARY KEY (`image_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_images`
--
ALTER TABLE `tbl_images`
  MODIFY `image_id` int(11) NOT NULL AUTO_INCREMENT;


database_connection.php


This PHP script will make Mysql database connection.


<?php

//database_connection.php

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

?>


index.php


This index file of this source code in this file you can find following things.

  • HTML form for select multiple images from local computer space with image selection validation.
  • jQuery script for submit form data to PHP script using Ajax.
  • Selected image has been send to PHP script using new FormData() object.
  • Ajax script send request for images and display on web page.



<!DOCTYPE html>  
<html>  
    <head>  
        <title>Webslesson Tutorial | Insert Multiple Images into Mysql Database using PHP</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">  
   <h3 align="center">Insert Multiple Images into Mysql Database using PHP</h3>  
            <br />  
            <form method="post" id="upload_multiple_images" enctype="multipart/form-data">
                <input type="file" name="image[]" id="image" multiple accept=".jpg, .png, .gif" />
                <br />
                <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
            </form>
            <br />  
            <br />
   
            <div id="images_list"></div>
            
        </div>  
    </body>  
</html>  
<script>  
$(document).ready(function(){

    load_images();

    function load_images()
    {
        $.ajax({
            url:"fetch_images.php",
            success:function(data)
            {
                $('#images_list').html(data);
            }
        });
    }
 
    $('#upload_multiple_images').on('submit', function(event){
        event.preventDefault();
        var image_name = $('#image').val();
        if(image_name == '')
        {
            alert("Please Select Image");
            return false;
        }
        else
        {
            $.ajax({
                url:"insert.php",
                method:"POST",
                data: new FormData(this),
                contentType:false,
                cache:false,
                processData:false,
                success:function(data)
                {
                    $('#image').val('');
                    load_images();
                }
            });
        }
    });
 
});  
</script>





insert.php


This insert.php file, in this file you can find PHP script for Insert Multiple images into Mysql database. This file has received ajax request for insert multiple file into Mysql database. First, this script check there is any image file has been received or not, if received then it will check how many image insert has been received. After this this PHP script insert images into Mysql database. Before insert imag into mysql database, first it has convert into binary string format using file_get_contents() function and then at it has make insert query and run insert query and store multiple images into mysql database.


<?php

//insert.php

include('database_connection.php');

if(count($_FILES["image"]["tmp_name"]) > 0)
{
 for($count = 0; $count < count($_FILES["image"]["tmp_name"]); $count++)
 {
  $image_file = addslashes(file_get_contents($_FILES["image"]["tmp_name"][$count]));
  $query = "INSERT INTO tbl_images(images) VALUES ('$image_file')";
  $statement = $connect->prepare($query);
  $statement->execute();
 }
}


?>


fetch_images.php


This PHP script received Ajax request for retrieve images from Mysql database. This PHP script retrieve images from Mysql database and after this convert into HTML format and send to Ajax request. For convert binary string to images, here we have use base64_encode() function.


<?php

//fetch_images.php

include('database_connection.php');

$query = "SELECT * FROM tbl_images ORDER BY image_id DESC";

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

$output = '<div class="row">';

if($statement->execute())
{
 $result = $statement->fetchAll();

 foreach($result as $row)
 {
  $output .= '
  <div class="col-md-2" style="margin-bottom:16px;">
   <img src="data:image/jpeg;base64,'.base64_encode($row['images'] ).'" class="img-thumbnail" />
  </div>
  ';
 }
}

$output .= '</div>';

echo $output;

?>

Monday, 5 November 2018

Shopping Cart with Add Bulk Item into Cart using PHP Ajax



If you have seen eCommerce Website or Online stores sites, If it is user friendly, then it will increase conversion and websites usability. One small feature of your website will stand you top and it will convert into profitability. This is because all revenue of your website comes from buyer or users of websites, If your online shopping cart has some feature that are very useful to user and user friendly, user can easily understand and it's decrease user efforts for place an order on your website, then your website revenue will jump to high. For this we have to give some features to our shopping cart and decrease the flow of process, so buyer can easily use our website. For this here we have discuss one features for shopping cart, which will decrease Buyers efforts for place an order, an that feature is add multiple or bulk item into Shopping cart.

Now question arise how can buyer can add bulk or multiple product into his Shopping cart by single click. Here we will make simple script using PHP with Ajax in which we have step by step describe how user can add bulk product into Shopping cart by single click. For this we have use use Checkbox selection, by checkboxes user can select multiple item which he want to add into cart, once all item has been selected, then he can click on Add to cart button. Once he has click on add to cart button, all selected item will be added into his cart. This feature will improve our shopping cart output, before we have to click on single item add to cart button, then that product will be added into cart. For multiple product add into cart we have to click multiple time Add to cart button for add multiple product into Shopping cart. But this type of functionality will decrease the click on Add to cart button, and in single click all item has been added into Shopping Cart.

Add multiple or Bulk product into Shopping Cart using PHP with Ajax we are make here. In this post first we will load all product details from Mysql database and display on web page using Ajax request with PHP script. On product load, you can find checkbox selection for select multiple item. After this we have use PHP with Ajax for display shopping cart details. Here we have use PHP SESSION variable for store shopping cart details. So, this shopping cart detail we can fetch all pages of website and this details will not be remove on accidental page refresh. By Ajax with PHP script, it will fetch shopping cart details for SESSION variable and display on web page with single item remove button and clear shopping cart button. Buyer can select multiple or Bulk item for add into his cart. Once all item has been selected then all he can click on Add to cart button, and all item added into cart. If same item has been again add into cart, then that item quantity will be automatically increase. Here user can remove single item or all item from shopping cart. So, this is simple tutorial on Shopping cart with Add multiple product into Cart using PHP with Ajax. Below you can find complete source code of this tutorial.






Source Code


Database



--
-- Database: `test`
--

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

--
-- Table structure for table `tbl_product`
--

CREATE TABLE IF NOT EXISTS `tbl_product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  `price` double(10,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

--
-- Dumping data for table `tbl_product`
--

INSERT INTO `tbl_product` (`id`, `name`, `image`, `price`) VALUES
(1, 'Samsung J2 Pro', '1.jpg', 100.00),
(2, 'HP Notebook', '2.jpg', 299.00),
(3, 'Panasonic T44 Lite', '3.jpg', 125.00);


index.php



<?php
//index.php
?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Ajax Shopping Cart by using Bootstrap Popover</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>
  .popover
  {
      width: 100%;
      max-width: 800px;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center"><a href="#">PHP Ajax Shopping Cart with Add Multiple Item into Cart</a></h3>
   <br />
   
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">Cart Details</div>
      <div class="col-md-6" align="right">
       <button type="button" name="clear_cart" id="clear_cart" class="btn btn-warning btn-xs">Clear</button>
      </div>
     </div>
    </div>
    <div class="panel-body" id="shopping_cart">

    </div>
   </div>

   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">Product List</div>
      <div class="col-md-6" align="right">
       <button type="button" name="add_to_cart" id="add_to_cart" class="btn btn-success btn-xs">Add to Cart</button>
      </div>
     </div>
    </div>
    <div class="panel-body" id="display_item">

    </div>
   </div>
  </div>
 </body>
</html>

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

 load_product();

 load_cart_data();
    
 function load_product()
 {
  $.ajax({
   url:"fetch_item.php",
   method:"POST",
   success:function(data)
   {
    $('#display_item').html(data);
   }
  });
 }

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

 $(document).on('click', '.select_product', function(){
  var product_id = $(this).data('product_id');
  if($(this).prop('checked') == true)
  {
   $('#product_'+product_id).css('background-color', '#f1f1f1');
   $('#product_'+product_id).css('border-color', '#333');
  }
  else
  {
   $('#product_'+product_id).css('background-color', 'transparent');
   $('#product_'+product_id).css('border-color', '#ccc');
  }
 });

 $('#add_to_cart').click(function(){
  var product_id = [];
  var product_name = [];
  var product_price = [];
  var action = "add";
  $('.select_product').each(function(){
   if($(this).prop('checked') == true)
   {
    product_id.push($(this).data('product_id'));
    product_name.push($(this).data('product_name'));
    product_price.push($(this).data('product_price'));
   }
  });

  if(product_id.length > 0)
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{product_id:product_id, product_name:product_name, product_price:product_price, action:action},
    success:function(data)
    {
     $('.select_product').each(function(){
      if($(this).prop('checked') == true)
      {
       $(this).attr('checked', false);
       var temp_product_id = $(this).data('product_id');
       $('#product_'+temp_product_id).css('background-color', 'transparent');
       $('#product_'+temp_product_id).css('border-color', '#ccc');
      }
     });

     load_cart_data();
     alert("Item has been Added into Cart");
    }
   });
  }
  else
  {
   alert('Select atleast one item');
  }

 });

 $(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",
    data:{product_id:product_id, action:action},
    success:function()
    {
     load_cart_data();
     alert("Item has been removed from Cart");
    }
   })
  }
  else
  {
   return false;
  }
 });

 $(document).on('click', '#clear_cart', function(){
  var action = 'empty';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{action:action},
   success:function()
   {
    load_cart_data();
    alert("Your Cart has been clear");
   }
  });
 });
    
});

</script>




database_connection.php



<?php

//database_connection.php

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

?>


fetch_item.php



<?php

//fetch_item.php

include('database_connection.php');

$query = "SELECT * FROM tbl_product ORDER BY id DESC";

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

if($statement->execute())
{
 $result = $statement->fetchAll();
 $output = '';
 foreach($result as $row)
 {
  $output .= '
  <div class="col-md-3" style="margin-top:12px;margin-bottom:12px;">  
            <div style="border:1px solid #ccc; border-radius:5px; padding:16px; height:300px;" align="center" id="product_'.$row["id"].'">
             <img src="images/'.$row["image"].'" class="img-responsive" /><br />
             <h4 class="text-info">
                        <div class="checkbox">
                              <label><input type="checkbox" class="select_product" data-product_id="'.$row["id"].'" data-product_name="'.$row["name"].'" data-product_price="'.$row["price"] .'" value="">'.$row["name"].'</label>
                        </div>
                  </h4>
             <h4 class="text-danger">$ '.$row["price"] .'</h4>
            </div>
        </div>
  ';
 }
 echo $output;
}

/*$output = '
<div class="col-md-3" style="margin-top:12px;">  
      <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
            <img src="https://image.ibb.co/jSR5Mn/1.jpg" class="img-responsive"><br>
            <h4 class="text-info">Samsung J2 Pro</h4>
            <h4 class="text-danger">$ 100.00</h4>
            <input type="text" name="quantity" id="quantity1" class="form-control" value="1">
            <input type="hidden" name="hidden_name" id="name1" value="Samsung J2 Pro">
            <input type="hidden" name="hidden_price" id="price1" value="100.00">
            <input type="button" name="add_to_cart" id="1" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart">
      </div>
</div>
            
            
            <div class="col-md-3" style="margin-top:12px;">  
            <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
                  <img src="https://image.ibb.co/mt5zgn/3.jpg" class="img-responsive"><br>
                  <h4 class="text-info">Panasonic T44 Lite</h4>
                  <h4 class="text-danger">$ 125.00</h4>
                  <input type="text" name="quantity" id="quantity3" class="form-control" value="1">
                  <input type="hidden" name="hidden_name" id="name3" value="Panasonic T44 Lite">
                  <input type="hidden" name="hidden_price" id="price3" value="125.00">
                  <input type="button" name="add_to_cart" id="3" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart">
            </div>
        </div>
            
            
            <div class="col-md-3" style="margin-top:12px;">  
            <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
                  <img src="https://image.ibb.co/b57C1n/2.jpg" class="img-responsive"><br>
                  <h4 class="text-info">HP Notebook</h4>
                  <h4 class="text-danger">$ 299.00</h4>
                  <input type="text" name="quantity" id="quantity2" class="form-control" value="1">
                  <input type="hidden" name="hidden_name" id="name2" value="HP Notebook">
                  <input type="hidden" name="hidden_price" id="price2" value="299.00">
                  <input type="button" name="add_to_cart" id="2" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart">
            </div>
        </div><div class="col-md-3" style="margin-top:12px;">  
            <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px; height:350px;" align="center">
                  <img src="https://image.ibb.co/eDhqnS/4.jpg" class="img-responsive"><br>
                  <h4 class="text-info">Wrist Watch</h4>
                  <h4 class="text-danger">$ 85.00</h4>
                  <input type="text" name="quantity" id="quantity4" class="form-control" value="1">
                  <input type="hidden" name="hidden_name" id="name4" value="Wrist Watch">
                  <input type="hidden" name="hidden_price" id="price4" value="85.00">
                  <input type="button" name="add_to_cart" id="4" style="margin-top:5px;" class="btn btn-success form-control add_to_cart" value="Add to Cart">
            </div>
        </div>
';

echo $output;*/

?>


fetch_cart.php



<?php

//fetch_cart.php

session_start();

$total_price = 0;
$total_item = 0;

$output = '
<div class="table-responsive" id="order_table">
 <table class="table table-bordered table-striped">
  <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"]))
{
 foreach($_SESSION["shopping_cart"] as $keys => $values)
 {
  $output .= '
  <tr>
   <td>'.$values["product_name"].'</td>
   <td>'.$values["product_quantity"].'</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_price = $total_price + ($values["product_quantity"] * $values["product_price"]);
  //$total_item = $total_item + 1;
 }
 $output .= '
 <tr>  
        <td colspan="3" align="right">Total</td>  
        <td align="right">$ '.number_format($total_price, 2).'</td>  
        <td></td>  
    </tr>
 ';
}
else
{
 $output .= '
    <tr>
     <td colspan="5" align="center">
      Your Cart is Empty!
     </td>
    </tr>
    ';
}
$output .= '</table></div>';

echo $output;
//echo '<pre>';
//print_r($_SESSION["shopping_cart"]);
//echo '</pre>';


?>


action.php



<?php

//action.php

session_start();

if(isset($_POST["action"]))
{
 if($_POST["action"] == "add")
 {
  $product_id = $_POST["product_id"];
  $product_name = $_POST["product_name"];
  $product_price = $_POST["product_price"];
  for($count = 0; $count < count($product_id); $count++)
  {
   $cart_product_id = array_keys($_SESSION["shopping_cart"]);
   if(in_array($product_id[$count], $cart_product_id))
   {
    $_SESSION["shopping_cart"][$product_id[$count]]['product_quantity']++;
   }
   else
   {
    $item_array = array(
     'product_id'               =>     $product_id[$count],  
     'product_name'             =>     $product_name[$count],
     'product_price'            =>     $product_price[$count],
     'product_quantity'         =>     1
    );

    $_SESSION["shopping_cart"][$product_id[$count]] = $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]);
   }
  }
 }
 if($_POST["action"] == 'empty')
 {
  unset($_SESSION["shopping_cart"]);
 }
}

?>

Tuesday, 30 October 2018

User Registration and Login System in Codeigniter 3

Part 1



Part 2



Part 3



Part 4



Part 5



Part 6



Part 7




User authentication is a required feature of any Web application. Based on user authentication user can access the system by providing their user authentication details. So, in this post we are login to learn Complete user registration and login system in Codeigniter framework. If you have use Codeigniter Framework to your web project, then in that project you want to add give rights to user to register into your system, after completed registration process, user can login into system by providing his login details which he has used in registration process. If login details are proper then user can access system. So here we will make complete user authentication system in Codeigniter in which user can registration into system and login into system features. Here you can learn this login and registration functionality in Codeigniter framework.

If you are start learning Codeigniter framework for web devlopment, then you must have to learn User Register and Login system which is most required feature of any web based application, so you have to must learn this system in Codeigniter, so you can make web based application in Codeigniter in which you can add this User register and Login system. Codeigniter framework has many build-in libraries and helper class which will very helpful to make user authentication system. In this post we will use Codeigniter database library, session library, form validation library, email library for sending verification email address link, encrypt library for convert simple password into hash formatted password. We will also use Codeigniter url helper, form helper for make this user register and login system in Codeigniter framework.

Here we will make user registration and login system using Session in Codeigniter framework. In this post you can find step by step process for make user registration and login system in Codeigniter with Session library with Mysql database. In this system you can find following features of User Registration and Login system using Codeigniter framework with Mysql database.


  • User Registration form to submit user details and Insert into Mysql Database
  • Send email verification email to registered email address for email verification
  • Convert user simple password to hash string for user authentication
  • Register and Login form data validation
  • Check email already registered or not at the time of user registration
  • User login form for access into system
  • Store user authentication details in Session
  • User logout from system



Database table creation


For store user information, we have to required table in mysql table, following script will make table in mysql database.


--
-- Database: `testing`
--

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

--
-- Table structure for table `codeigniter_register`
--

CREATE TABLE `codeigniter_register` (
  `id` int(11) NOT NULL,
  `name` varchar(250) NOT NULL,
  `email` varchar(250) NOT NULL,
  `password` text NOT NULL,
  `verification_key` varchar(250) NOT NULL,
  `is_email_verified` enum('no','yes') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `codeigniter_register`
--
ALTER TABLE `codeigniter_register`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `codeigniter_register`
--
ALTER TABLE `codeigniter_register`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;


Autoload Libraries & Helper


In User Register and Login system in Codeigniter, we have to load some libraries and helper at the time of first code execution. For this we have to open application/cofig/autoload.php file and load following files and helper.

autoload.php

$autoload['libraries'] = array('session','database');
$autoload['helper'] = array('url','form');







Database Connection


After load of required library and helper, we want to make database connection, for this we have to open application/config/database.php file and write following database configuration.

database.php

<?php

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'testing',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

?>


Controllers (Register.php)


This controller is used for handles all register replated functionality.
_construct() - This function is used for load form validation and encrypt library, register model at the time of new object of this class has been created.
index() - This function will load register form in browser.
validation() - This function has received register form request, in this function first we have validate form data using Codeigniter form validation library. After success validation of form data, it will proceed for insert data into mysql table. After successfully insert of register form data, this function will generate dynamic email verification email with dynamic email verification link and send email to registered email address using Codeigniter email library.
verify_email() - This function is used for verify email address, this function received request for email verification from email verification link. Once email has been verified user can login into system.


<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Register extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  if($this->session->userdata('id'))
  {
   redirect('private_area');
  }
  $this->load->library('form_validation');
  $this->load->library('encrypt');
  $this->load->model('register_model');
 }

 function index()
 {
  $this->load->view('register');
 }

 function validation()
 {
  $this->form_validation->set_rules('user_name', 'Name', 'required|trim');
  $this->form_validation->set_rules('user_email', 'Email Address', 'required|trim|valid_email|is_unique[codeigniter_register.email]');
  $this->form_validation->set_rules('user_password', 'Password', 'required');
  if($this->form_validation->run())
  {
   $verification_key = md5(rand());
   $encrypted_password = $this->encrypt->encode($this->input->post('user_password'));
   $data = array(
    'name'  => $this->input->post('user_name'),
    'email'  => $this->input->post('user_email'),
    'password' => $encrypted_password,
    'verification_key' => $verification_key
   );
   $id = $this->register_model->insert($data);
   if($id > 0)
   {
    $subject = "Please verify email for login";
    $message = "
    <p>Hi ".$this->input->post('user_name')."</p>
    <p>This is email verification mail from Codeigniter Login Register system. For complete registration process and login into system. First you want to verify you email by click this <a href='".base_url()."register/verify_email/".$verification_key."'>link</a>.</p>
    <p>Once you click this link your email will be verified and you can login into system.</p>
    <p>Thanks,</p>
    ";
    $config = array(
     'protocol'  => 'smtp',
     'smtp_host' => 'smtpout.secureserver.net',
     'smtp_port' => 80,
     'smtp_user'  => 'xxxxxxx', 
                  'smtp_pass'  => 'xxxxxxx', 
     'mailtype'  => 'html',
     'charset'    => 'iso-8859-1',
                   'wordwrap'   => TRUE
    );
    $this->load->library('email', $config);
    $this->email->set_newline("\r\n");
    $this->email->from('info@webslesson.info');
    $this->email->to($this->input->post('user_email'));
    $this->email->subject($subject);
    $this->email->message($message);
    if($this->email->send())
    {
     $this->session->set_flashdata('message', 'Check in your email for email verification mail');
     redirect('register');
    }
   }
  }
  else
  {
   $this->index();
  }
 }

 function verify_email()
 {
  if($this->uri->segment(3))
  {
   $verification_key = $this->uri->segment(3);
   if($this->register_model->verify_email($verification_key))
   {
    $data['message'] = '<h1 align="center">Your Email has been successfully verified, now you can login from <a href="'.base_url().'login">here</a></h1>';
   }
   else
   {
    $data['message'] = '<h1 align="center">Invalid Link</h1>';
   }
   $this->load->view('email_verification', $data);
  }
 }

}

?>


Controllers(Login.php)


In this Login controller you can find following function for all Login operation like, load login form, login form data verification.

_construct() - This function is used for load form validation and encrypt library, login model at the time of new object of this class has been created.
index() - This function will load Login form on web page.
validation() - This function received request for validate login details. After successfully verify user login details, page will redirect to private_area controller.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  if($this->session->userdata('id'))
  {
   redirect('private_area');
  }
  $this->load->library('form_validation');
  $this->load->library('encrypt');
  $this->load->model('login_model');
 }

 function index()
 {
  $this->load->view('login');
 }

 function validation()
 {
  $this->form_validation->set_rules('user_email', 'Email Address', 'required|trim|valid_email');
  $this->form_validation->set_rules('user_password', 'Password', 'required');
  if($this->form_validation->run())
  {
   $result = $this->login_model->can_login($this->input->post('user_email'), $this->input->post('user_password'));
   if($result == '')
   {
    redirect('private_area');
   }
   else
   {
    $this->session->set_flashdata('message',$result);
    redirect('login');
   }
  }
  else
  {
   $this->index();
  }
 }

}

?>


Controller(Private_area.php)


After successfully validate login details page has been redirect to this controller. In this there following function.
_construct() - This function is used validate used login or not into system, if user not login into system then this function will redirect page to login form.
index() - This function will display Welcome user message with Logout page link.
logout() - This function will remove all session value, this function will logout user from system and redirect to login form.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Private_area extends CI_Controller {
 public function __construct()
 {
  parent::__construct();
  if(!$this->session->userdata('id'))
  {
   redirect('login');
  }
 }

 function index()
 {
  echo '<br /><br /><br /><h1 align="center">Welcome User</h1>';
  echo '<p align="center"><a href="'.base_url().'private_area/logout">Logout</a></p>';
 }

 function logout()
 {
  $data = $this->session->all_userdata();
  foreach($data as $row => $rows_value)
  {
   $this->session->unset_userdata($row);
  }
  redirect('login');
 }
}

?>


Models(Register_model.php)


insert() - Models function is used for database operation, So this function will insert data into Mysql table.
verify_email($key) - This model function has been used for database operation for verify email address.


<?php
class Register_model extends CI_Model
{
 function insert($data)
 {
  $this->db->insert('codeigniter_register', $data);
  return $this->db->insert_id();
 }

 function verify_email($key)
 {
  $this->db->where('verification_key', $key);
  $this->db->where('is_email_verified', 'no');
  $query = $this->db->get('codeigniter_register');
  if($query->num_rows() > 0)
  {
   $data = array(
    'is_email_verified'  => 'yes'
   );
   $this->db->where('verification_key', $key);
   $this->db->update('codeigniter_register', $data);
   return true;
  }
  else
  {
   return false;
  }
 }
}

?>


Models(Login_model.php)


In this model there is only one function can_login($email, $password), this function is used to verify login form details with Mysql table details, If login details match then it will return true, otherwise it will return error message. This function convert hash password to simple string and match with Login form password.


<?php
class Login_model extends CI_Model
{
 function can_login($email, $password)
 {
  $this->db->where('email', $email);
  $query = $this->db->get('codeigniter_register');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    if($row->is_email_verified == 'yes')
    {
     $store_password = $this->encrypt->decode($row->password);
     if($password == $store_password)
     {
      $this->session->set_userdata('id', $row->id);
     }
     else
     {
      return 'Wrong Password';
     }
    }
    else
    {
     return 'First verified your email address';
    }
   }
  }
  else
  {
   return 'Wrong Email Address';
  }
 }
}

?>


Views(register.php)


This html output file, which output we view on web page in browser. It will load register form on web page. In this file we have make register form, in which we have use set_value() form helper function, by using this function it can remember form data on form again load on validation error. Same way we have also use form_error() form validation library function for display form validation error on web page. Below you can find complete source code of registration form.


<!DOCTYPE html>
<html>
<head>
 <title>Complete User Registration and Login System in Codeigniter</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>

<body>
 <div class="container">
  <br />
  <h3 align="center">Complete User Registration and Login System in Codeigniter</h3>
  <br />
  <div class="panel panel-default">
   <div class="panel-heading">Register</div>
   <div class="panel-body">
    <form method="post" action="<?php echo base_url(); ?>register/validation">
     <div class="form-group">
      <label>Enter Your Name</label>
      <input type="text" name="user_name" class="form-control" value="<?php echo set_value('user_name'); ?>" />
      <span class="text-danger"><?php echo form_error('user_name'); ?></span>
     </div>
     <div class="form-group">
      <label>Enter Your Valid Email Address</label>
      <input type="text" name="user_email" class="form-control" value="<?php echo set_value('user_email'); ?>" />
      <span class="text-danger"><?php echo form_error('user_email'); ?></span>
     </div>
     <div class="form-group">
      <label>Enter Password</label>
      <input type="password" name="user_password" class="form-control" value="<?php echo set_value('user_password'); ?>" />
      <span class="text-danger"><?php echo form_error('user_password'); ?></span>
     </div>
     <div class="form-group">
      <input type="submit" name="register" value="Register" class="btn btn-info" />
     </div>
    </form>
   </div>
  </div>
 </div>
</body>
</html>


Views(email_verification.php)


This view file is used for display success message of email verification with Login link.


<!DOCTYPE html>
<html>
<head>
 <title>Complete Login Register system in Codeigniter</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>

<body>
 <div class="container">
  <br />
  <h3 align="center">Complete Login Register system in Codeigniter</h3>
  <br />
  
  <?php

  echo $message;
  
  ?>
  
 </div>
</body>
</html>


Views(login.php)


This view file will load Login form on web page.


<!DOCTYPE html>
<html>
<head>
    <title>Complete User Registration and Login System in Codeigniter</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>

<body>
    <div class="container">
        <br />
        <h3 align="center">Complete User Registration and Login System in Codeigniter</h3>
        <br />
        <div class="panel panel-default">
            <div class="panel-heading">Login</div>
            <div class="panel-body">
                <?php
                if($this->session->flashdata('message'))
                {
                    echo '
                    <div class="alert alert-success">
                        '.$this->session->flashdata("message").'
                    </div>
                    ';
                }
                ?>
                <form method="post" action="<?php echo base_url(); ?>login/validation">
                    <div class="form-group">
                        <label>Enter Email Address</label>
                        <input type="text" name="user_email" class="form-control" value="<?php echo set_value('user_email'); ?>" />
                        <span class="text-danger"><?php echo form_error('user_email'); ?></span>
                    </div>
                    <div class="form-group">
                        <label>Enter Password</label>
                        <input type="password" name="user_password" class="form-control" value="<?php echo set_value('user_password'); ?>" />
                        <span class="text-danger"><?php echo form_error('user_password'); ?></span>
                    </div>
                    <div class="form-group">
                        <input type="submit" name="login" value="Login" class="btn btn-info" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="<?php echo base_url(); ?>register">Register</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

So, this is complete source code of Codeigniter Login Register system, if you have any question regarding this tutorial, you can comment into comment box.

Monday, 29 October 2018

Top Languages to Develop Mobile Apps



Mobile development game is fierce. From UI to safe payment gateways, these apps need to be perfect, or they will never be able to lure customers in. We all know how brutal people can be on app stores with their reviews; even the slightest glitch and shortcoming, is unacceptable.

Furthermore, with new technologies coming every year- AR, VR, etc.- the pressure mounts on developers to find ways to employ these technologies in their apps to compete in the market. To make all of this happen, the selection of a proper programming language is crucial. Now the choice of a programming language depends on various aspects, prime of them is the type of app you are building- Native, Web or Hybrid. Furthermore, the business model used by your employer will have a significant influence on this decision as well. All the app requirements and targets have to be crystal clear between both parties involved before the development phase starts. Based on this plan, you can choose the most suitable programming language to develop that app.

Listed below, in no particular order, are the five best programming languages for mobile app development.

Swift


Swift is a multi-paradigm, compiled programming language used to develop iOS and MacOS apps. Up until a few years ago, iOS and MacOS developers used Objective-C to develop these apps, but with the coming of Swift, Objective-C has lost a lot of its popularity and has taken the back burner. Swift makes writing codes for Apple’s latest APIs such as Cocoa Touch and Cocoa, smoother and easier. Furthermore, Swift helps you in bypassing various security vulnerabilities which weres posed in codebases written in Objective-C.

More and more developers are opting for Swift nowadays to develop iOS and MacOS apps, and you might want to switch to it too, given the fact that it is so widely and warmly embraced by the developer community.

Java


Because of its traits like code reusability and portability, Java is without any doubt, the best programming language to develop Native Android and Cross-platform apps. Java enables programmer in writing codes which can run on multiple platforms and environments, a feature which is always preferable over a rigid codebase. Moreover, Java is a widely known language, and there is a horde of programmers out there who are already very proficient in it, so finding a Java programmer is not a very hard task either. Java has a big online community which provides open source support and libraries to developers.

HTML5


HTML5 is the best programming language to develop mobile apps which are web-fronted. HTML5 makes developing hybrid apps easier by folds by allowing developers to insert many data types very easily and it supports different screen sizes as well. But the biggest problem with HTML5 is that it is still a proposed standard. But apart from this little problem, HTML5 provides a fantastic option for developers to develop mobile apps which are strictly budget constrained.

C++


Old is gold; this is probably the best and shortest way to describe C++ 's market position. C++ is one of the oldest game pieces on the board. Over the years, it has managed to survive while many languages came and went without leaving any mark on the world. The reason behind it is that even though C++ is not trendy and stylish, C++ is robust, generates highly portable code base and is fast.




Kotlin


Kotlin is an open source language which is based on JVM (Java Virtual Machine) which was created specifically to develop Android apps. Though Kotlin is a new player in the market, it has gained significant popularity and is a part of the latest iteration of Android Studio- Android Studio 3.0.

Kotlin is able to do everything Java can; then one might ask- what was the need of coming up with it at all? The honest answer will be that Java has gotten old. Though it is still relevant and the top language to develop Android Apps, Kotlin is new, concise, tool-friendly and fixes many of Java’s shortcomings such as Null pointer references, etc.

Before We Go


In the end, the type of language you choose is directly dependent on the kind of app you want to develop, and your budget. Native apps are costly and take longer to be developed while Hybrid apps are cost effective and take less time. Choice of a programming language will influence your app greatly, and it is a good idea to make sure you have considered all the factors of the business before you make your final choice.

Author Bio: Arpita is an SEO expert providing her services to one of the highly acclaimed software studio, Matellio LLC. Her passion resides in sharing knowledge with the world and grow by keeping abreast of the latest industry facets. She has crafted some of the brilliant informative write-ups that have received great commendation.

Thursday, 25 October 2018

Live Mysql Data Search using AngularJS with PHP



If you want to make Mysql Live data search feature in AngularJS with PHP, then in this post you can find step by step guide for how to use AngularJS with PHP for implement mysql live data search functionality. Live data search means you can search mysql table data by entering your search query in textbox, and based on that query script will search data in mysql table all column and it will filter table data and display on web without page refresh. Because here we have use AngularJS for create live data search functionality.

If you have use Mysql database for store records, and you have fetch records from mysql table and display on web page in HTML table. Now you want to search data from large amount of data and display filter result on web page. At that time if you have implement live data search feature in your application then it will reduce your search efforts. It will display live data on web page when you have start type in textbox and based on your type text it filter data according which you have type in textbox.

In some our previous web tutorial we have already publish post on Live data search using ajax jquery, codeigniter and even laravel framework also. But we have not make tutorial on Live data search using AngularJS. There many web developer has use AngularJS as front end instead of jQuery. So, If you are beginner level of AngularJS developer, who has use PHP as backend. Then this post will help you to learn how to make live database search application in AngularJS with PHP.









Source Code


Create Database


Run following script in your PHPMyAdmin, it will make customer table in your database.


--
-- Database: `testing`
--

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

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

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

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

INSERT INTO `tbl_customer` (`CustomerID`, `CustomerName`, `Gender`, `Address`, `City`, `PostalCode`, `Country`) VALUES
(1, 'Maria Anders', 'Female', 'Obere Str. 57', 'Berlin', '12209', 'Germany'),
(2, 'Ana Trujillo', 'Female', 'Avda. de la Construction 2222', 'Mexico D.F.', '5021', 'Mexico'),
(3, 'Antonio Moreno', 'Male', 'Mataderos 2312', 'Mexico D.F.', '5023', 'Mexico'),
(4, 'Thomas Hardy', 'Male', '120 Hanover Sq.', 'London', 'WA1 1DP', 'United Kingdom'),
(5, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(6, 'Wolski Zbyszek', 'Male', 'ul. Filtrowa 68', 'Walla', '01-012', 'Poland'),
(7, 'Matti Karttunen', 'Male', 'Keskuskatu 45', 'Helsinki', '21240', 'Finland'),
(8, 'Karl Jablonski', 'Male', '305 - 14th Ave. S. Suite 3B', 'Seattle', '98128', 'United States'),
(9, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(10, 'John Koskitalo', 'Male', 'Torikatu 38', 'Oulu', '90110', 'Finland'),
(39, 'Ann Devon', 'Female', '35 King George', 'London', 'WX3 6FW', 'United Kingdom'),
(38, 'Janine Labrune', 'Female', '67, rue des Cinquante Otages', 'Nantes', '44000', 'Finland'),
(37, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(36, 'Elizabeth Brown', 'Female', 'Berkeley Gardens 12 Brewery', 'London', 'WX1 6LT', 'United Kingdom'),
(30, 'Trina Davidson', 'Female', '1049 Lockhart Drive', 'Barrie', 'ON L4M 3B1', 'Canada'),
(31, 'Jeff Putnam', 'Male', 'Industrieweg 56', 'Bouvignies', '7803', 'Belgium'),
(32, 'Joyce Rosenberry', 'Female', 'Norra Esplanaden 56', 'HELSINKI', '380', 'Finland'),
(33, 'Ronald Bowne', 'Male', '2343 Shadowmar Drive', 'New Orleans', '70112', 'United States'),
(34, 'Justin Adams', 'Male', '45, rue de Lille', 'ARMENTIERES', '59280', 'France'),
(35, 'Pedro Afonso', 'Male', 'Av. dos Lusiadas, 23', 'Sao Paulo', '05432-043', 'Brazil'),
(100, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(101, 'Tonia Sayre', 'Female', '84 Haslemere Road', 'ECHT', 'AB32 2DY', 'United Kingdom'),
(102, 'Loretta Harris', 'Female', 'Avenida Boavista 71', 'SANTO AMARO', '4920-111', 'Portugal'),
(103, 'Sean Wong', 'Male', 'Rua Vito Bovino, 240', 'Sao Paulo-SP', '04677-002', 'Brazil'),
(104, 'Frederick Sears', 'Male', 'ul. Marysiuska 64', 'Warszawa', '04-617', 'Poland'),
(105, 'Tammy Cantrell', 'Female', 'Lukiokatu 34', 'HAMEENLINNA', '13250', 'Finland'),
(106, 'Megan Kennedy', 'Female', '1210 Post Farm Road', 'Norcross', '30071', 'United States'),
(107, 'Maria Whittaker', 'Female', 'Spresstrasse 62', 'Bielefeld Milse', '33729', 'Germany'),
(108, 'Dorothy Parker', 'Female', '32 Lairg Road', 'NEWCHURCH', 'HR5 5DR', 'United Kingdom'),
(109, 'Roger Rudolph', 'Male', 'Avenida Julio Saul Dias 78', 'PENAFIEL', '4560-470', 'Portugal'),
(110, 'Karen Metivier', 'Female', 'Rua Guimaraes Passos, 556', 'Sao Luis-MA', '65025-450', 'Brazil'),
(111, 'Charles Hoover', 'Male', 'Al. Tysiaclecia 98', 'Warszawa', '03-851', 'Poland'),
(112, 'Becky Moss', 'Female', 'Laivurinkatu 6', 'MIKKELI', '50120', 'Finland'),
(113, 'Frank Kidd', 'Male', '2491 Carson Street', 'Cincinnati', 'KY 45202', 'United States'),
(114, 'Donna Wilson', 'Female', 'Hallesches Ufer 69', 'Dettingen', '73265', 'Germany'),
(115, 'Lillian Roberson', 'Female', '36 Iolaire Road', 'NEW BARN', 'DA3 3FT', 'United Kingdom');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_customer`
--
ALTER TABLE `tbl_customer`
  ADD PRIMARY KEY (`CustomerID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_customer`
--
ALTER TABLE `tbl_customer`
  MODIFY `CustomerID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=116;





index.php


In this file you can find front-end HTML code and AngularJS code for make Live Data search.


<?php

//index.php

?>
<!DOCTYPE html>
<html>
 <head>
  <title>AngularJS Live Data Search using PHP Mysql</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  .form_style
  {
   width: 600px;
   margin: 0 auto;
  }
  </style>
 </head>
 <body>
  
  <div class="container" ng-app="live_search_app" ng-controller="live_search_controller" ng-init="fetchData()">
   <br />
   <h3 align="center">AngularJS Live Data Search using PHP Mysql</h3>
   <br />
   <div class="form-group">
    <div class="input-group">
     <span class="input-group-addon">Search</span>
     <input type="text" name="search_query" ng-model="search_query" ng-keyup="fetchData()" placeholder="Search by Customer Details" class="form-control" />
    </div>
   </div>
   <br />
   <table class="table table-striped table-bordered">
    <thead>
     <tr>
      <th>Customer Name</th>
      <th>Gender</th>
      <th>Address</th>
      <th>City</th>
      <th>Postal Code</th>
      <th>Country</th>
     </tr>
    </thead>
    <tbody>
     <tr ng-repeat="data in searchData">
      <td>{{ data.CustomerName }}</td>
      <td>{{ data.Gender }}</td>
      <td>{{ data.Address }}</td>
      <td>{{ data.City }}</td>
      <td>{{ data.PostalCode }}</td>
      <td>{{ data.Country }}</td>
     </tr>
    </tbody>
   </table>
  </div>
  
 </body>
</html>

<script>
var app = angular.module('live_search_app', []);
app.controller('live_search_controller', function($scope, $http){
 $scope.fetchData = function(){
  $http({
   method:"POST",
   url:"fetch.php",
   data:{search_query:$scope.search_query}
  }).success(function(data){
   $scope.searchData = data;
  });
 };
});
</script>


fetch.php


In this PHP file, you can find PHP script for search or filter data in Mysql table or all data from mysql table. This script has received Ajax request for search data and send data in json format.


<?php

//fetch.php


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

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

$query = '';
$data = array();

if(isset($form_data->search_query))
{
 $search_query = $form_data->search_query;
 $query = "
 SELECT * FROM tbl_customer 
 WHERE (CustomerName LIKE '%$search_query%' 
 OR Address LIKE '%$search_query%' 
 OR City LIKE '%$search_query%' 
 OR PostalCode LIKE '%$search_query%' 
 OR Country LIKE '%$search_query%') 
 OR Gender = '$search_query'
 ";
}
else
{
 $query = "SELECT * FROM tbl_customer ORDER BY CustomerName ASC";
}

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

if($statement->execute())
{
 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }
 echo json_encode($data);
}

?>


This is complete source of AngularJS Live data search using PHP and Mysql. If you have any query regarding this post, you can comment in comment box.

Tuesday, 23 October 2018

Export to Excel, PDF, CSV From jQuery Datatables using PHP Ajax



Do you know jQuery Datatables supports to exports it's data to different file format like Excel sheet, CSV (comma-separated values) and PDF by using PHP script with Ajax. That means if we have use jQuery Datatables plugin has been use for display our dynamic data in tabular format on web page then it is very easy for us to export jQuery Datatables data to Excel, CSV and PDF file format.

Currently we want to make Excel, CSV or PDF file from HTML table we have to mainually copy data from webpage to different file and make CSV or Excel or PDF file for our data. But this jQuery Datatables plugin has feature for export table data into different file format like Excel, CSV, PDF. We want to just enable this feature in Datatables at the time of initialization of this plugin. We have to add some jQuery Datables library for enable this feature.

So, In this post you can find Data exporting functionality by using jQuery Datatables plugin with PHP script and Ajax. There are many viewers has request us to add this type of tutorial, so we have publish this tutorial on our website. In this tutorial we have step by step describe how to export data from jQuery Datatables to Excel sheet, CSV file, Copy into Clipboart and make PDF file from Data using PHP script with Ajax.

If you want to use this data export feature in your project, so first you have to load all data on web page, because this functionality only export only those data which we can see on web page. So for export all data to different file we want to first load on web page then after we can export into Excel, CSV, PDF. Otherwise it will export only those data which we can see on web page, not export whole data to Excel or CSV or PDF file format.









Source Code


database_connection.php


First we have to make database connection, so we can fetch data from Mysql database and display on webpage.


<?php

//database_connection.php

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

?>


index.php


After making of database connection, We have to go to index.php file, here we can see we have imported jQuery Datatables library for enable export button feature for this we have to import following library into our index.php file.


<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.css"/>
  <script type="text/javascript" src="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.js"></script>


By using this library we can enable export button feature in jQuery Datatables. After this we have define HTML table for initialization jQuery Datatable plugin on this page based on id selectore #customer_data. After this we have initialize this plugin by using Datatable() method. In this method we have define Ajax request which has been send to fetch.php for fetch data from Mysql table display on web page. For make export button we have add dom: 'lBfrtip', option. This option will make export button above jQuery Datatable and for button name we have add buttons option. In this option we can define which button we want to display on web page. This whole source code you can find below.


<html>
 <head>
  <title>Export jQuery Datatables Data to Excel, CSV, PDF using PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.css"/>
  <script type="text/javascript" src="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.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 box">
   <h3 align="center">Export jQuery Datatables Data to Excel, CSV, PDF using PHP Ajax</h3>
   <br />
   <div class="table-responsive">
    <table id="customer_data" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>Customer Name</th>
       <th>Gender</th>
       <th>Address</th>
       <th>City</th>
       <th>Postal Code</th>
       <th>Country</th>
      </tr>
     </thead>
    </table>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>

<script type="text/javascript" language="javascript" >
 $(document).ready(function(){

  $('#customer_data').DataTable({
   "processing" : true,
   "serverSide" : true,
   "ajax" : {
    url:"fetch.php",
    type:"POST"
   },
   dom: 'lBfrtip',
   buttons: [
    'excel', 'csv', 'pdf', 'copy'
   ],
   "lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ]
  });
  
 });
 
</script>


fetch.php


This file has received ajax request for fetch data from Mysql database. Here you can find complete PHP script for fetch data from Mysql table and send this data to Ajax request in json format.


<?php

//fetch.php

include('database_connection.php');

$column = array('CustomerName', 'Gender', 'Address', 'City', 'PostalCode', 'Country');

$query = "SELECT * FROM tbl_customer ";

if(isset($_POST['search']['value']))
{
 $query .= '
 WHERE CustomerName LIKE "%'.$_POST['search']['value'].'%" 
 OR Gender LIKE "%'.$_POST['search']['value'].'%" 
 OR Address LIKE "%'.$_POST['search']['value'].'%" 
 OR City LIKE "%'.$_POST['search']['value'].'%" 
 OR PostalCode LIKE "%'.$_POST['search']['value'].'%" 
 OR Country LIKE "%'.$_POST['search']['value'].'%" 
 ';
}

if(isset($_POST['order']))
{
 $query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
 $query .= 'ORDER BY CustomerID DESC ';
}

$query1 = '';

if($_POST['length'] != -1)
{
 $query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

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

$statement->execute();

$number_filter_row = $statement->rowCount();

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

$statement->execute();

$result = $statement->fetchAll();

$data = array();

foreach($result as $row)
{
 $sub_array = array();
 $sub_array[] = $row['CustomerName'];
 $sub_array[] = $row['Gender'];
 $sub_array[] = $row['Address'];
 $sub_array[] = $row['City'];
 $sub_array[] = $row['PostalCode'];
 $sub_array[] = $row['Country'];
 $data[] = $sub_array;
}

function count_all_data($connect)
{
 $query = "SELECT * FROM tbl_customer";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $statement->rowCount();
}

$output = array(
 'draw'    => intval($_POST['draw']),
 'recordsTotal'  => count_all_data($connect),
 'recordsFiltered' => $number_filter_row,
 'data'    => $data
);

echo json_encode($output);

?>






Database


By using below SQL script you can make customer table in your database.


--
-- Database: `testing`
--

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

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

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

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

INSERT INTO `tbl_customer` (`CustomerID`, `CustomerName`, `Gender`, `Address`, `City`, `PostalCode`, `Country`) VALUES
(1, 'Maria Anders', 'Female', 'Obere Str. 57', 'Berlin', '12209', 'Germany'),
(2, 'Ana Trujillo', 'Female', 'Avda. de la Construction 2222', 'Mexico D.F.', '5021', 'Mexico'),
(3, 'Antonio Moreno', 'Male', 'Mataderos 2312', 'Mexico D.F.', '5023', 'Mexico'),
(4, 'Thomas Hardy', 'Male', '120 Hanover Sq.', 'London', 'WA1 1DP', 'United Kingdom'),
(5, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(6, 'Wolski Zbyszek', 'Male', 'ul. Filtrowa 68', 'Walla', '01-012', 'Poland'),
(7, 'Matti Karttunen', 'Male', 'Keskuskatu 45', 'Helsinki', '21240', 'Finland'),
(8, 'Karl Jablonski', 'Male', '305 - 14th Ave. S. Suite 3B', 'Seattle', '98128', 'United States'),
(9, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(10, 'John Koskitalo', 'Male', 'Torikatu 38', 'Oulu', '90110', 'Finland'),
(39, 'Ann Devon', 'Female', '35 King George', 'London', 'WX3 6FW', 'United Kingdom'),
(38, 'Janine Labrune', 'Female', '67, rue des Cinquante Otages', 'Nantes', '44000', 'Finland'),
(37, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(36, 'Elizabeth Brown', 'Female', 'Berkeley Gardens 12 Brewery', 'London', 'WX1 6LT', 'United Kingdom'),
(30, 'Trina Davidson', 'Female', '1049 Lockhart Drive', 'Barrie', 'ON L4M 3B1', 'Canada'),
(31, 'Jeff Putnam', 'Male', 'Industrieweg 56', 'Bouvignies', '7803', 'Belgium'),
(32, 'Joyce Rosenberry', 'Female', 'Norra Esplanaden 56', 'HELSINKI', '380', 'Finland'),
(33, 'Ronald Bowne', 'Male', '2343 Shadowmar Drive', 'New Orleans', '70112', 'United States'),
(34, 'Justin Adams', 'Male', '45, rue de Lille', 'ARMENTIERES', '59280', 'France'),
(35, 'Pedro Afonso', 'Male', 'Av. dos Lusiadas, 23', 'Sao Paulo', '05432-043', 'Brazil'),
(100, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(101, 'Tonia Sayre', 'Female', '84 Haslemere Road', 'ECHT', 'AB32 2DY', 'United Kingdom'),
(102, 'Loretta Harris', 'Female', 'Avenida Boavista 71', 'SANTO AMARO', '4920-111', 'Portugal'),
(103, 'Sean Wong', 'Male', 'Rua Vito Bovino, 240', 'Sao Paulo-SP', '04677-002', 'Brazil'),
(104, 'Frederick Sears', 'Male', 'ul. Marysiuska 64', 'Warszawa', '04-617', 'Poland'),
(105, 'Tammy Cantrell', 'Female', 'Lukiokatu 34', 'HAMEENLINNA', '13250', 'Finland'),
(106, 'Megan Kennedy', 'Female', '1210 Post Farm Road', 'Norcross', '30071', 'United States'),
(107, 'Maria Whittaker', 'Female', 'Spresstrasse 62', 'Bielefeld Milse', '33729', 'Germany'),
(108, 'Dorothy Parker', 'Female', '32 Lairg Road', 'NEWCHURCH', 'HR5 5DR', 'United Kingdom'),
(109, 'Roger Rudolph', 'Male', 'Avenida Julio Saul Dias 78', 'PENAFIEL', '4560-470', 'Portugal'),
(110, 'Karen Metivier', 'Female', 'Rua Guimaraes Passos, 556', 'Sao Luis-MA', '65025-450', 'Brazil'),
(111, 'Charles Hoover', 'Male', 'Al. Tysiaclecia 98', 'Warszawa', '03-851', 'Poland'),
(112, 'Becky Moss', 'Female', 'Laivurinkatu 6', 'MIKKELI', '50120', 'Finland'),
(113, 'Frank Kidd', 'Male', '2491 Carson Street', 'Cincinnati', 'KY 45202', 'United States'),
(114, 'Donna Wilson', 'Female', 'Hallesches Ufer 69', 'Dettingen', '73265', 'Germany'),
(115, 'Lillian Roberson', 'Female', '36 Iolaire Road', 'NEW BARN', 'DA3 3FT', 'United Kingdom');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_customer`
--
ALTER TABLE `tbl_customer`
  ADD PRIMARY KEY (`CustomerID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_customer`
--
ALTER TABLE `tbl_customer`
  MODIFY `CustomerID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=116;


So, this is complete source code of How to export jQuery Datatables data to Excel, CSV, PDF and Copy in Clipboard using PHP Ajax. If you have any query regarding this tutorial you can comment in comment box.

Friday, 19 October 2018

Delete Multiple Records using PHP Ajax with Animated Effect



In this post you can find how to delete or remove multiple records using PHP Ajax with jQuery Animated effect without refresh of web page. In this tutorial for select multiple data we have use HTML checkbox input field, because by using this field we can select multiple records at the same time and based on that selection we will delete multiple mysql table data using Ajax with Animated effect using jQuery.

One of our previous post in which we have already discuss how to update multiple data using PHP Ajax with checkbox selection. By using this same concept we have make this tutorial for delete multiple data using PHP Ajax with checkbox selection. But here we have add some extra functionality like Animated effect which will increase UI appearance. So when user has select multiple data for delete or remove then he can know which data he has selected for deletion. Because once data has been deleted then it cannot be recovered. So, by using this Animated effect he can know which data he has selected for deletion purpose and it will reduce to delete wrong data by accidently.

Here we have make Live multiple records delete application using PHP Ajax jQuery and Mysql. In which you can Live delete multiple records by Checkbox selection with jQuery Animated Effect. Here for front-end Animated effect and send request to server we have use combine jQuery and Ajax and for backend for delete data from mysql database we have use PHP script. By combine all this here we have make delete multiple records in single click with Animated effect using PHP Ajax jQuery. Below you can find step by step source of this tutorial.










Source Code


Create Table


Run following Sql script in your PHPMyAdmin, this script will make tbl_employee in your selected database.


--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_employee`
--

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` text NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(100) NOT NULL,
  `age` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`) VALUES
(5, 'Clara Gilliam', '63 Woodridge Lane\r\nMemphis, TN 38138', 'Female', 'Programmer', 24),
(6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26),
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 32),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 38),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 64),
(177, 'Patricia L. Scott', '1584 Dennison Street\r\nModesto, CA 95354', 'Female', 'Urban and regional planner', 54),
(181, 'Kimberly J. Ellis', '4905 Holt Street\r\nFort Lauderdale, FL 33301', 'Male', 'Dressing room attendant', 24),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29),
(186, 'Louis C. Charmis', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 40),
(190, 'Michael Cobb', '2409 Patterson Fork Road, Westchester, IL 60154', 'Female', 'Personal secretary', 36);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=197;


database_connection.php


Once table has been created in your database, so now for make this application, you have to make database connection. For this you have to open database_connection.php file make write following code. It will make database connection.


<?php

//database_connection.php

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

?>


index.php


After making database connection, in this index.php file, first you can find code for fetch data from employee table and display on web page in table format. In this code you can check dynamic checkbox has been created for each row and in that we have store row id data. Below you can also find jquery code for checkbox selection and delete button click. When we have click on checkbox then .removeRow class has been added into particular table row, and when we have click on delete button then ajax request has been send to delete.php file. After successfully delete of data from mysql database, select table row has been remove by using jQuery fadeOut() method.


<?php

//index.php

include('database_connection.php');

$query = "SELECT * FROM tbl_employee ORDER BY id DESC";

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

$statement->execute();

$result = $statement->fetchAll();

?>

<html>  
    <head>  
        <title>Delete Multiple Records using PHP Ajax with Animated Effect</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 />
   <div class="table-responsive">  
    <h3 align="center">Delete Multiple Records using PHP Ajax with Animated Effect</h3><br />
    <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th width="5%"><button type="button" name="delete_all" id="delete_all" class="btn btn-danger btn-xs">Delete</button></th>
                            <th width="20%">Name</th>
                            <th width="38%">Address</th>
                            <th width="7%">Gender</th>
                            <th width="25%">Designation</th>
                            <th width="5%">Age</th>
                        </tr>
                        </thead>
                        <?php
                        foreach($result as $row)
                        {
                            echo '
                            <tr>
                                <td>
                                    <input type="checkbox" class="delete_checkbox" value="'.$row["id"].'" />
                                </td>
                                <td>'.$row["name"].'</td>
                                <td>'.$row["address"].'</td>
                                <td>'.$row["gender"].'</td>
                                <td>'.$row["designation"].'</td>
                                <td>'.$row["age"].'</td>
                            </tr>
                            ';
                        }
                        ?>
                    </table>
                </div>
   </div>  
  </div>
    </body>  
</html> 
<style>
.removeRow
{
    background-color: #FF0000;
    color:#FFFFFF;
}
</style>
<script>  
$(document).ready(function(){ 

    $('.delete_checkbox').click(function(){
        if($(this).is(':checked'))
        {
            $(this).closest('tr').addClass('removeRow');
        }
        else
        {
            $(this).closest('tr').removeClass('removeRow');
        }
    });

    $('#delete_all').click(function(){
        var checkbox = $('.delete_checkbox:checked');
        if(checkbox.length > 0)
        {
            var checkbox_value = [];
            $(checkbox).each(function(){
                checkbox_value.push($(this).val());
            });

            $.ajax({
                url:"delete.php",
                method:"POST",
                data:{checkbox_value:checkbox_value},
                success:function()
                {
                    $('.removeRow').fadeOut(1500);
                }
            });
        }
        else
        {
            alert("Select atleast one records");
        }
    });

});  
</script>


delete.php


This is the last file of this source code and this file has received Ajax request for delete multiple records and it will run PHP script for delete multiple data.


<?php

//delete.php

include('database_connection.php');

if(isset($_POST["checkbox_value"]))
{
 for($count = 0; $count < count($_POST["checkbox_value"]); $count++)
 {
  $query = "DELETE FROM tbl_employee WHERE id = '".$_POST['checkbox_value'][$count]."'";
  $statement = $connect->prepare($query);
  $statement->execute();
 }
}


?>


This is the complete source code of this tutorial. If you have still any query regarding this post, you can tell in comment box. Keep visiting Webslesson.info for new web development tutorial.