Thursday, 4 October 2018

Data Encryption and Decryption In CodeIgniter

Data Encryption and Decryption In CodeIgniter - 1



Data Encryption and Decryption In CodeIgniter - 2



Data Encryption and Decryption In CodeIgniter - 3




Do you know what is data encryption and decryption in Web development, so we have explain you data encryption and decryption is to convert plain text into random alphanumeric with special character and that string has no any meaning. So when data store into Mysql database then it has been encrypted and when that data we want see on web page then that will be converted into plain string format in it's original meaning.

Most of web developers has used data encryption for store their highly secured data like password, credit card number OTP etc. Because this type of data is very important, so if someone has hack this data then he can misuse this type data. For this we have to store this type of data in encryption form, so if someone has hack our data then he cannot use this type of data because it has been store in encrytion form and it this can be decrypted by using encryption key which has been used for decrypt this data.

If you have used Codeigniter framework for your web development, then data encryption and decryption will be much easier than using simple PHP script. Because Codeigniter has it's own encryption library for encrypt and decrypt data. You has to just load library and use that library function then data will be easily encrypted and decrypted.

Now one question aris in your mind how can we load Codeigniter encryption library, for this you have to write following code, this code will load encryption library in your code environment.


<?php

$this->load->library('encrypt');

?>







Once this library has been load then by using this encrypt library object we can access different method of data encryption and decryption of this library by using this $this->encrypt. Before using this library in our working code for data encrypt and decrypt, first we have to set the encryption key in our Codeigniter framework. This key is used by different library and helper of Codeigniter like Session, Encrypt etc. By using this key it has cryptographic process and based on this key it has encrypt and decrypt data. That means data will be plain text to encrypted form by using key and from encryted form to plain text by using this encryption key. So, once you has define this key then after you do not change this key otherwise your encrypted data will be lost.

This is simple key in which we can use random character with alphanumeric and not plain string and it must be 32 characters long. For define this encryption key we have go to application/config/config.php file. In this file you have to file below code and define your encryption key.


<?php

$config['encryption_key'] = "YOUR KEY"; 

?>


After define your encryption key in your Codeigniter framwork, now we can use Encrypt library of Codeigniter for data encryption and decryption. For convert plain text to encrypted string we can use following method of encrypt library of Codeigniter.


<?php

$this->encrypt->encode()

?>


Once data has been encrypted and store in database, now again we want to convert into plain text form. For this we can use following method of Encrypt library of Codeigniter.


<?php

$this->encrypt->decode();

?>


Now you want to learn how can we use this encrypt library for data encryption and decryption in real example, so below we have make simple example of Codeigniter Crud, in which we have define step by step how data will be encrypted when it has been insert into Mysql data. That means we have define How can we insert encrypted data into Mysql database by using Codeigniter Encrypt Library.

Once encypted data has been store into Mysql database, now we want to display encrypted data on web page in plain text form. So by using Codeigniter Encrypt library we have define how can we fetch encrypted data from Mysql database and display on web page in plain text form in tabular format. Here we have also define how can we Codeigniter Encrypt library for edit or update encrypted data. Below you can find complete source code code for Insert Update and Fetch encyrption and decryption data in Codeigniter.

Database


Following script will help you to make table in your Mysql database.







--
-- Database: `testing`
--

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

--
-- Table structure for table `sample_data`
--

CREATE TABLE `sample_data` (
  `id` int(10) NOT NULL,
  `first_name` text NOT NULL,
  `last_name` text NOT NULL,
  `age` text NOT NULL,
  `gender` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_data`
--
ALTER TABLE `sample_data`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;


Controllers - EncryptionDecryption.php


This is controllers source code, in which you can find code for Insert data, Fetch data and Update data. How can we have load Encrypt Library and how we have use encode() and decode() method of Encrypt library for data encryption and decryption.


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

class EncryptionDecryption extends CI_Controller {

 function index()
 {
  $this->load->model('encryptiondecryption_model');
  $this->load->library('encrypt');
  $data['data'] = $this->encryptiondecryption_model->fetch_data();
  $this->load->view('encryption_decryption', $data);
 }
 
 function insert()
 {
  $this->load->view('insert_data');
 }

 function insert_validation()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('first_name', 'First Name', 'required|trim');
  $this->form_validation->set_rules('last_name', 'Last Name', 'required|trim');
  $this->form_validation->set_rules('age', 'Age', 'required|numeric|trim');
  $this->form_validation->set_rules('gender', 'Gender', 'required|trim');
  if($this->form_validation->run() == false)
  {
   $this->insert();
  }
  else
  {
   $this->load->library('encrypt');

   $data = array(
    'first_name' => $this->encrypt->encode($this->input->post('first_name')),
    'last_name'  => $this->encrypt->encode($this->input->post('last_name')),
    'age'   => $this->encrypt->encode($this->input->post('age')),
    'gender'  => $this->encrypt->encode($this->input->post('gender')),
   );
   $this->load->model('encryptiondecryption_model');
   $this->encryptiondecryption_model->insert($data);
   $this->session->set_flashdata('action', 'Data Inserted');
   redirect('encryptiondecryption');
  }
 }

 function edit()
 {
  $this->load->library('encrypt');
  $this->load->model('encryptiondecryption_model');
  $data['data'] = $this->encryptiondecryption_model->fetch_single_data($this->uri->segment(3));
  $this->load->view('edit_data', $data);
 }

 function edit_validation()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('first_name', 'First Name', 'required|trim');
  $this->form_validation->set_rules('last_name', 'Last Name', 'required|trim');
  $this->form_validation->set_rules('age', 'Age', 'required|numeric|trim');
  $this->form_validation->set_rules('gender', 'Gender', 'required|trim');
  if($this->form_validation->run() == false)
  {
   $this->edit();
  }
  else
  {
   $this->load->library('encrypt');

   $data = array(
    'first_name' => $this->encrypt->encode($this->input->post('first_name')),
    'last_name'  => $this->encrypt->encode($this->input->post('last_name')),
    'age'   => $this->encrypt->encode($this->input->post('age')),
    'gender'  => $this->encrypt->encode($this->input->post('gender')),
   );
   $this->load->model('encryptiondecryption_model');

   $this->encryptiondecryption_model->edit($this->input->post('hidden_id'), $data);

   $this->session->set_flashdata('action', 'Data Updated');
   redirect('encryptiondecryption');
  }
 }
 
}

?>


Models - EncryptionDecryption_model.php


This is Mysql database side operation code for Insert data into Mysql table, fetch single data and select all data from Mysql table and update or edit data option.


<?php
class EncryptionDecryption_model extends CI_Model
{
 function insert($data)
 {
  $this->db->insert('sample_data', $data);
 }

 function fetch_data()
 {
  $this->db->order_by('id', 'DESC');
  $query = $this->db->get('sample_data');
  return $query;
 }

 function fetch_single_data($id)
 {
  $this->db->where('id', $id);
  return $this->db->get('sample_data');
 }

 function edit($id, $data)
 {
  $this->db->where('id', $id);
  $this->db->update('sample_data', $data);
 }
}

?>


Views - insert_data.php


This is views file source code and below file will display insert data form on web page page and this page has been load by insert() method of Controller.


<html>
<head>
    <title>Codeigniter Encryption and Decryption - Insert Data</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
    {
     background-color: #f1f1f1;
    }
    .box
    {
     width: 600px;
     margin:0 auto;
     background-color: #fff;
     border:1px solid #ccc;
     border-radius: 5px;
     padding:16px;
    }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <br />
  <div class="box">
   <h3 align="center">Codeigniter3 Encryption and Decryption - Insert Data</h3>
   <br />
            <?php
            if(validation_errors() != '')
            {
                echo '
                <div class="alert alert-danger alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    ' . validation_errors() .'
                </div>
                ';
            }
            ?>
   <form method="post" action="<?php echo base_url(); ?>encryptiondecryption/insert_validation">
                <input type="text" name="first_name" class="form-control" placeholder="Enter First Name" />
                <br />
                <input type="text" name="last_name" class="form-control" placeholder="Enter Last Name" />
                <br />
                <input type="text" name="age" class="form-control" placeholder="Enter Age" />
                <br />
                <select name="gender" class="form-control">
                    <option value="male">Male</option>
                    <option value="female">Female</option>
                </select>
                <br />
                <div align="center">
                    <input type="submit" name="insert" class="btn btn-primary" value="Insert" />
                </div>
            </form>
  </div>
  <br />
 </div>
</body>
</html>


Views - encyption_decryption.php


This view file will display all mysql data in plain text form on web page in tabular format with edit button link and this file has been load by using index() method of Controller.


<html>
<head>
    <title>Codeigniter Encryption and Decryption - Fetch Data</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
    {
     background-color: #f1f1f1;
    }
    .box
    {
     width: 800px;
     margin:0 auto;
     background-color: #fff;
     border:1px solid #ccc;
     border-radius: 5px;
     padding:16px;
    }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <br />
  <div class="box">
   <h3 align="center">Codeigniter3 Encryption and Decryption - Fetch Data</h3>
   <br />
   <div class="table-responsive">
   <?php
   if($this->session->flashdata('action'))
   {
    echo '
    <div class="alert alert-success alert-dismissible">
      <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      '.$this->session->flashdata('action').'
     </div>
    ';
   }
   ?>
    <div align="right">
     <a href="<?php echo base_url(); ?>encryptiondecryption/insert" class="btn btn-primary btn-sm">Add</a>
    </div>
    <br />
    <table class="table table-striped table-bordered">
     <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Age</th>
      <th>Gender</th>
      <th>Edit</th>
     </tr>
     <?php
     foreach($data->result() as $row)
     {
      echo '
      <tr>
       <td>'.$this->encrypt->decode($row->first_name).'</td>
       <td>'.$this->encrypt->decode($row->last_name).'</td>
       <td>'.$this->encrypt->decode($row->age).'</td>
       <td>'.$this->encrypt->decode($row->gender).'</td>
       <td><a href="'.base_url().'encryptiondecryption/edit/'.$row->id.'">Edit</a></td>
      </tr>
      ';
     }
     ?>
    </table>
   </div>
  </div>
  <br />
 </div>
</body>
</html>


Views - edit_data.php


This views files has been used for edit or update data, it will load form with filled data for update and this file has been load by using edit() method of controller.


<html>
<head>
    <title>Codeigniter Encryption and Decryption - Update Data</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
    {
     background-color: #f1f1f1;
    }
    .box
    {
     width: 600px;
     margin:0 auto;
     background-color: #fff;
     border:1px solid #ccc;
     border-radius: 5px;
     padding:16px;
    }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <br />
  <div class="box">
   <h3 align="center">Codeigniter3 Encryption and Decryption - Update Data</h3>
   <br />
   <?php

            foreach($data->result() as $row)
            {
            ?>
            <script>
            $(document).ready(function(){
                $('#gender').val("<?php echo $this->encrypt->decode($row->gender); ?>");
            });
            </script>
            <form method="post" action="<?php echo base_url(); ?>encryptiondecryption/edit_validation">
                <input type="text" name="first_name" class="form-control" placeholder="Enter First Name" value="<?php echo $this->encrypt->decode($row->first_name); ?>" />
                <br />
                <input type="text" name="last_name" class="form-control" placeholder="Enter Last Name" value="<?php echo $this->encrypt->decode($row->last_name);?>" />
                <br />
                <input type="text" name="age" class="form-control" placeholder="Enter Age" value="<?php echo $this->encrypt->decode($row->age); ?>" />
                <br />
                <select name="gender" id="gender" class="form-control">
                    <option value="male">Male</option>
                    <option value="female">Female</option>
                </select>
                <br />
                <div align="center">
                    <input type="hidden" name="hidden_id" value="<?php echo $row->id; ?>" />
                    <input type="submit" name="insert" class="btn btn-primary" value="Edit" />
                </div>
            </form>
            <?php
            }

            ?>
  </div>
  <br />
 </div>
</body>
</html>


If you want to download complete file of this Insert Update and Fetch encrypted and decrypted data in Codeigniter tutorial, then you can download complete source code file by click on below download link.




Friday, 28 September 2018

Pop-up Login Form If Session Expired using PHP Ajax



This is the most common feature of any website, if user has accidentally logout from system or his session has been expired and in browser still open website inner page then login modal has been popup for prevent to access inner pages of website without login into system. This type of feature we have make in this post by using PHP with Ajax. So, If Session has been expired or Session timeout then automatically login modal form will be pop up on web page to prevent to access website inner pages, and without login into system user cannot access that open page. This type of functionality is for accidentally logout from system in one tab or browser and in another website private pages has been open. So, in that pages login modal form will be popup on web page to tell user you are logout from system and if you want to access this you want to again login into system. In most of current website use this type of feature for accidentally logout from system or session timeout or expired.

If you have make website using PHP then you can easily implement this type of functionality into your system, so it will add one new feature in your website. You can easily build this type of feature in PHP using Ajax and jQuery. By using Ajax jQuery with PHP we can easily popup login modal form on web page when PHP session timeout. In this post we have step by step describe how best way we can handle Session expired with Ajax and popup login modal form for give notification to user your logout from system and to access system you have to login again into system on web page.

First we have to make simple login form for get access into system, For make login form we have use Ajax with PHP for validate user details. When user have filled login details then Ajax request will be send to check_login.php file to validate user information is proper or not. If details is not proper then it will display error on login page otherwise page will be redirect to index.php. Below you can find source code for login.php and check_login.php.



Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_login`
--

CREATE TABLE `tbl_login` (
  `id` int(11) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `gender` varchar(30) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  `address` text NOT NULL,
  `mobile_no` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_login`
--

INSERT INTO `tbl_login` (`id`, `first_name`, `last_name`, `gender`, `email`, `password`, `address`, `mobile_no`) VALUES
(1, 'John', 'Smith', 'male', 'johnsmith@gmail.com', '$2y$10$vgo3NI5w5cLB74E4B2sdVuKwdSpJL/EAeKSUdevkc/j3zl0sJAf5i', 'test address', '9632587410');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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


login.php



<?php  

//login.php
session_start();
if(isset($_SESSION["name"]))
{
 header('location:index.php');
}

?>  
<!DOCTYPE html>  
<html>  
    <head>  
  <title>Login Modal Popup After Session Timeout in PHP using Ajax</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
  {
   background-color:#f1f1f1;
  }
        #box  
        {  
            width:500px;
   background-color:#ffffff;
            margin:0 auto;  
            padding:16px;  
            text-align:center;  
            margin-top:50px;
   border:1px solid #ccc;
   border-radius:5px;
        }  
        </style>  
 </head>  
 <body>  
  <div class="container">
   <br />
   <br />
   <h1 align="center">Login Modal Popup After Session Timeout in PHP using Ajax</h1>
   <div id="box">
    <h2>Login</h2>
    <br />
    <span id="error_message"></span>
    <form method="post" id="login_form">
     <input type="text" name="email" placeholder="Enter Email" class="form-control" required /><br />
     <input type="password" name="password" placeholder="Enter Password" class="form-control" required /><br />
     <input type="submit" name="submit" id="submit" class="btn btn-info" value="Login" />
    </form>
    <br /><br />  
   </div>
  </div>
    </body>  
</html>

<script>
$(document).ready(function(){
 $('#login_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"check_login.php",
   method:"POST",
   data:$(this).serialize(),
   success:function(data){
    if(data != '')
    {
     $('#error_message').html(data);
    }
    else
    {
     window.location = 'index.php';
    }
   }
  })
 });
});
</script>


check_login.php



<?php

//check_login.php

if(isset($_POST["email"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

 session_start();

 $query = "SELECT * FROM tbl_login WHERE email = '".$_POST['email']."'";

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

 $statement->execute();

 $total_row = $statement->rowCount();

 $output = '';

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

  foreach($result as $row)
  {
   if(password_verify($_POST["password"], $row["password"]))
   {
    $_SESSION["name"] = $row["first_name"];
   }
   else
   {
    $output = '<label class="text-danger">Wrong Password</label>';
   }
  }
 }
 else
 {
  $output = '<label class="text-danger">Wrong Email Address</label>';
 }

 echo $output;
}

?>








In check_login.php page we can see for validate password details we have use password_verify() function, because in database password has been stored under hash format, so for validate hash password we have use password_verify() function and user first name details has been store into $_SESSION variable for check user has login into system and this variable value we can access from any page of system.

Once user has successfully login into system then he will be redirect to index page. On this page can be view only to login user for this we have check $_SESSION variable value is set or not, if this variable value is set then he can view this page otherwise it will be redirect to login page again. But if $_SESSION variable value is set then he can access this page, now here we will make login modal code and make one jQuery function for check user $_SESSION variable value is set or not.

index.php



<!DOCTYPE html>  
<html>  
    <head>  
        <title>Login Modal Popup After Session Timeout in PHP using Ajax</title> 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
        <style>  
        #box  
        {  
            width:600px;
            color:white;  
            margin:0 auto;  
            padding:10px;  
            text-align:center;  
        }  
        </style>  
    </head>  
    <body>
 <br />

    <?php  
    session_start();  
    if(isset($_SESSION["name"]))
    {  
  echo "<h1 align='center'>Login Modal Popup After Session Timeout in PHP using Ajax</h1>";
        echo "<h1 align='center'>".$_SESSION["name"]."</h1>";  
        echo "<p align='center'><a href='logout.php'>Logout</a></p>";  
    }  
    else  
    {  
        header('location:login.php');  
    }  
    ?>  
    </body>  
</html>

<div class="modal fade" id="loginModal" role="dialog">
    <div class="modal-dialog modal-sm">
  <div class="modal-content">
   <div class="modal-header">
    <h4 class="modal-title">Session Expired Login Again</h4>
   </div>
   <div class="modal-body">
    <form method="post" id="login_form">  
     <input type="text" name="email" placeholder="Enter Email" class="form-control" required /><br />  
     <input type="password" name="password" placeholder="Enter Password" class="form-control" required /><br />  
     <input type="submit" name="submit" id="submit" class="btn btn-info" value="Login" />  
    </form>
   </div>
  </div>
    </div>
</div>

<script>  
$(document).ready(function(){
 
 var is_session_expired = 'no';
    function check_session()
    {
        $.ajax({
            url:"check_session.php",
            method:"POST",
            success:function(data)
            {
    if(data == '1')
    {
     $('#loginModal').modal({
      backdrop: 'static',
      keyboard: false,
     });
     is_session_expired = 'yes';
    }
   }
        })
    }
 
 var count_interval = setInterval(function(){
        check_session();
  if(is_session_expired == 'yes')
  {
   clearInterval(count_interval);
  }
    }, 10000);
 
 $('#login_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"check_login.php",
   method:"POST",
   data:$(this).serialize(),
   success:function(data){
    if(data != '')
    {
     $('#error_message').html(data);
    }
    else
    {
     location.reload();
    }
   }
  });
 });

});  
</script>


Here in index.php file we have make login modal form with id #loginModal. This modal will be popup if PHP Session expired and for check Session timeout or not. For this here we have make check_session() function which send Ajax on every 10 seconds to check_session.php for check Session variable value expired or not. For call check_session() on every seconds we have use setInterval() method. By using this method it will call jQuery function every 10 seconds. Once modal has been popup then after stop to called check_session() we have use clearInterval() method.

check_session.php



<?php  
 
//check_session.php
 
session_start();

if(isset($_SESSION["name"]))
{
 echo '0';
}
else
{
 echo '1';
}

?>


This is PHP script to check $_SESSION variable value is set or not for check session timeout using isset() function. Lastly for logout from system below you can find logout.php code. In which session variable value has been destroy using session_destroy() function. After logout from system page will be redirect to login.php.


<?php  

//logout.php
 
session_start();

session_destroy();

header("location:login.php");

?>


This is complete step by step process for how to create feature like Login form popup on web page if user Session timeout or expired using PHP script with Ajax jQuery.

Wednesday, 26 September 2018

Insert Tree View Node using PHP Ajax



One of our previous post on Make Treeview from Mysql data by using Bootstrap Treeview plugin with PHP and Ajax and that post has received huge response from readers and request us to make this type of Dynamic Treeview in which we can add or create new node dynamically and make dynamic treeview hierarchical stucture using same Bootstrap plugin using PHP and Ajax. So, in this post we have add this topic in which you can learn how can we add or insert new node dynamically in Treeview using PHP Mysql Ajax and Boostrap Treeview plugin. By using this tutorial user can create multi level treeview node dynamically.

Bootstrap Tree view is a easy solution for display of hierarchical tree structures in the form of Tree View node and by using this plugin we can create multi level tree view nodes static or dynamically. For use this plugin we have to required jQuery library and Bootstrap library with this plugin library. This plugin has been initialize by using treeview() method and in this method data option is required, without data it will not display Tree view on web page. So, for initialize this plugin data is required in json format. Data must be in below format.


[  
    {  
        "text":"Chemicals",
        "nodes":[  
            {  
                "text":"Inorganic chemicals",
                "nodes":[  

                ]
            },
            {  
                "text":"Organic Chemicals",
                "nodes":[  

                ]
            }
        ]
    },
    {  
        "text":"Electronics",
        "nodes":[  
            {  
                "text":"Laptop",
                "nodes":[  
                    {  
                        "text":"Dell",
                        "nodes":[  
                            {  
                                "text":"i3 Processor",
                                "nodes":[  

                                ]
                            },
                            {  
                                "text":"i5 Processors",
                                "nodes":[  

                                ]
                            },
                            {  
                                "text":"i7 Processors",
                                "nodes":[  

                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
]


If data in above format then it will display above data in treeview form on web page. In this post we have take an example of category and display that category data in Treeview format. For create new node first we have make simple form for enter data into mysql table. Once data has been inserted into Mysql table then it will be added into parent category select box also. After insert of new data we want to add new not in Treeview. For this we have make one fill_treeview() function, this function has been fetch data from mysql table in JSON format and convert into treeview stucture using treeview() function. Below you can find complete source code of this tutorial which helps you to know how to add or create new node in Tree view with Bootstrap Tree view plugin using PHP Mysql and Ajax.









Source Code



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_category`
--

CREATE TABLE `tbl_category` (
  `category_id` int(11) NOT NULL,
  `category_name` varchar(200) NOT NULL,
  `parent_category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_category`
--

INSERT INTO `tbl_category` (`category_id`, `category_name`, `parent_category_id`) VALUES
(2, 'Chemicals', 0),
(3, 'Inorganic chemicals', 2),
(4, 'Organic Chemicals', 2),
(5, 'Electronics', 0),
(6, 'Laptop', 5),
(7, 'Dell', 6),
(8, 'i3 Processor', 7),
(9, 'i5 Processors', 7),
(10, 'i7 Processors', 7);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_category`
--
ALTER TABLE `tbl_category`
  ADD PRIMARY KEY (`category_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_category`
--
ALTER TABLE `tbl_category`
  MODIFY `category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;






index.php



<!DOCTYPE html>
<html>
 <head>
  <title>How to Add New Node in Dynamic Treeview using PHP Mysql Ajax</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 type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css" />
  <style>
  </style>
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:900px;">
   <h2 align="center">How to Add New Node in Dynamic Treeview using PHP Mysql Ajax</h2>
   <br /><br />
   <div class="row">
    <div class="col-md-6">
     <h3 align="center"><u>Add New Category</u></h3>
     <br />
     <form method="post" id="treeview_form">
      <div class="form-group">
       <label>Select Parent Category</label>
       <select name="parent_category" id="parent_category" class="form-control">
       
       </select>
      </div>
      <div class="form-group">
       <label>Enter Category Name</label>
       <input type="text" name="category_name" id="category_name" class="form-control">
      </div>
      <div class="form-group">
       <input type="submit" name="action" id="action" value="Add" class="btn btn-info" />
      </div>
     </form>
    </div>
    <div class="col-md-6">
     <h3 align="center"><u>Category Tree</u></h3>
     <br />
     <div id="treeview"></div>
    </div>
   </div>
  </div>
 </body>
</html>
<script>
 $(document).ready(function(){

  fill_parent_category();

  fill_treeview();
  
  function fill_treeview()
  {
   $.ajax({
    url:"fetch.php",
    dataType:"json",
    success:function(data){
     $('#treeview').treeview({
      data:data
     });
    }
   })
  }

  function fill_parent_category()
  {
   $.ajax({
    url:'fill_parent_category.php',
    success:function(data){
     $('#parent_category').html(data);
    }
   });
   
  }

  $('#treeview_form').on('submit', function(event){
   event.preventDefault();
   $.ajax({
    url:"add.php",
    method:"POST",
    data:$(this).serialize(),
    success:function(data){
     fill_treeview();
     fill_parent_category();
     $('#treeview_form')[0].reset();
     alert(data);
    }
   })
  });
 });
</script>


database_connection.php



<?php

//database_connection.php

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

?>


fill_parent_category.php



<?php

//fill_parent_category.php

include('database_connection.php');

$query = "SELECT * FROM tbl_category ORDER BY category_name ASC";

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

$statement->execute();

$result = $statement->fetchAll();

$output = '<option value="0">Parent Category</option>';

foreach($result as $row)
{
 $output .= '<option value="'.$row["category_id"].'">'.$row["category_name"].'</option>';
}

echo $output;

?>


add.php



<?php

//add.php

include('database_connection.php');

$data = array(
 ':category_name'  => $_POST['category_name'],
 ':parent_category_id' => $_POST['parent_category']
);

$query = "
 INSERT INTO tbl_category (category_name, parent_category_id) VALUES (:category_name, :parent_category_id)
";

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

if($statement->execute($data))
{
 echo 'Category Added';
}


?>


fetch.php



<?php

//fetch.php

include('database_connection.php');

$parent_category_id = 0;

$query = "SELECT * FROM tbl_category";

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

$statement->execute();

$result = $statement->fetchAll();

foreach($result as $row)
{
 $data = get_node_data($parent_category_id, $connect);
}

echo json_encode(array_values($data));

function get_node_data($parent_category_id, $connect)
{
 $query = "SELECT * FROM tbl_category WHERE parent_category_id = '".$parent_category_id."'";

 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = array();
 foreach($result as $row)
 {
  $sub_array = array();
  $sub_array['text'] = $row['category_name'];
  $sub_array['nodes'] = array_values(get_node_data($row['category_id'], $connect));
  $output[] = $sub_array;
 }
 return $output;
}

?>

Tuesday, 25 September 2018

Why Is It Important To Pursue Web Development Small Business ?



Small business owners usually have a small budget, as they using small business accounting software their profit will go with time. With the onset of technology and networks, our life is majority based on computer networks. Lots of startup business are struggling to establish their business in the market. The reason why many business covering failure because they depreciate the power of web presence. They need to create an effective web presence now, at the initial stage of business, in order to be adept to get a decent profit in the future. So if you have just started your small business, the sooner you create a website, the sooner you’ll get a profit.

5 Reasons Your Small Business Needs A Website



  • Show up in Google search results
  • Wider audience reaches due to website accessibility
  • Showcase your product and services
  • Collect customer information
  • Low budget web development

Show up in Google search results


There are 80 % of customers who perform online research before making a purchase. They search for one or more keywords in Google like “best sports shoes”. If you don’t have a website then your chances in google search results will be zero. But if you have your own website then you can optimize it for search engines, thereby increasing your chances of appearing at the top of Google’s results and getting more visibility with potential customers. You can customize your site with long-tail keywords, meta descriptions, and titles to improve your search engine optimization.

Wider audience reaches due to website accessibility.


Even if your physical shop is closed but your online business is running for 24/7, your sales will continue to be on the market and this will attract more customers to your business. One more reason to build a web presence for your business is an abatement of distances. A website allows you to expand your target audience and make deals with customers who are away from you. Actually, the whole globe is within your reach.

Showcase your product and services


In today’s generation more customers preferring to find and buy products online, having a website that showcases your products and services is important

It actualizes two conveniences :

  • Customers will find your products online and purchase them instantly
  • Customers will find their products online and then visit your store to make a purchase.





For example, merrchant, best small business accounting software, is an accounting software run by Raletta Grad. Without a brick-and-mortar storefront, Raletta relies on their website to attract visitors and convert them into paying customers.

Collect customer information


A business website is a platform for learning about your audience. It opens an opportunity to collect information about your customers. There are so many pieces of information you can collect it with your customers like name, email address, mobile number, street address, and many more of your site visitors to learn who about who visits your website.

Low budget web development


The budget for small business people is always small. So their business progresses gradually. If they want to bring profit into their business then they will have to connect to the web development, in order to get a decent profit in the future. Low budget web development allows you to access a simple but efficient website, able to convert visitors into clients. It's quite affordable for startups and small business to create a minimum viable product to quickly appear on the market and then invest in its improvements later on.

Saturday, 22 September 2018

Simple Way to Sending an Email in Laravel

If you are beginner level of Laravel framework programmer, then from this post you can learn something new like How can we send an in Laravel. Because any web application sending of email from application is required feature or functionality. So, If you have make any web application in Laravel then you should required to put send an email from your web application. For this here you can find step by step guid how to make simple contact form in Laravel framework and when user submit contact form details then email should be received to owner of website.

Laravel is an robust PHP framework and it has most of all functionality which we would required to make any robust web application. For send an email it has popular SwiftMailer library and by using this library we can get an advantage of different email driver for send an email. Here for send an email we will make one mailable which will handle all email setting. Once this class has been ready then we should define email configuration like host name, port, driver, username and password details under .env file. Below you can find step by step process for best way to sending an email from your Laravel application.




Step 1 - Install Laravel Application


First we have to download Laravel application, for we have to go to command prompt and in this first we should run composer command which handle all dependency of Laravel and after write following command. This command will download Laravel and install into defined folder.


composer create-project laravel/laravel student_crud


Step 2 - Create Controller


Once Laravel framework successfully installed then after we have to first make a controller for handle http request. For this we have to command prompt and write following command. This command will make SendEmailController.php file in app/Http/Controllers.


php artisan make:controller SendEmailController


After create controller in this we have make index() method for load view file in which we will make contact form. This method will load resources/views/send_email.blade.php
file in browser.
app/Http/Controllers/SendEmailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SendEmailController extends Controller
{
    function index()
    {
     return view('send_email');
    }
}


Step 3 - Create View Contact Form


Now we would make view file for display contact form on web page. Below you can find source code of contact form view file.

resouces/views/send_email.blade.php

<!DOCTYPE html>
<html>
 <head>
  <title>How Send an Email in Laravel</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>
  <style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
    border:1px solid #ccc;
   }
   .has-error
   {
    border-color:#cc0000;
    background-color:#ffff99;
   }
  </style>
 </head>
 <body>
  <br />
  <br />
  <br />
  <div class="container box">
   <h3 align="center">How Send an Email in Laravel</h3><br />
   @if (count($errors) > 0)
    <div class="alert alert-danger">
     <button type="button" class="close" data-dismiss="alert">×</button>
     <ul>
      @foreach ($errors->all() as $error)
       <li>{{ $error }}</li>
      @endforeach
     </ul>
    </div>
   @endif
   @if ($message = Session::get('success'))
   <div class="alert alert-success alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>
           <strong>{{ $message }}</strong>
   </div>
   @endif
   <form method="post" action="{{url('sendemail/send')}}">
    {{ csrf_field() }}
    <div class="form-group">
     <label>Enter Your Name</label>
     <input type="text" name="name" class="form-control" value="" />
    </div>
    <div class="form-group">
     <label>Enter Your Email</label>
     <input type="text" name="email" class="form-control" value="" />
    </div>
    <div class="form-group">
     <label>Enter Your Message</label>
     <textarea name="message" class="form-control"></textarea>
    </div>
    <div class="form-group">
     <input type="submit" name="send" class="btn btn-info" value="Send" />
    </div>
   </form>
   
  </div>
 </body>
</html>


Above we can see in Contact form view file we have use jQuery and Bootstrap library for make simple contact form. Laravel use blade template for write server script code between html code. So here we can see validation error message code and success form submission message on web page. Once user has filled all form details then form submission request has been send to send() method of SendEmailController.php controller file which we can see below.


<form method="post" action="{{url('sendemail/send')}}">






Step 4 - Set Route


In this framework we should set the rule of each method which we have created under Controller file. So here we will make two method like index() and send() method under controller. For this we have to go to routes/web.php for set the route.


<?php

Route::get('/sendemail', 'SendEmailController@index');
Route::post('/sendemail/send', 'SendEmailController@send');

?>


Step 5 - Create Mailable Class


Before make mailable class we should define email configuration in .env file of Laravel framework.


MAIL_DRIVER=smtp
MAIL_HOST=smtpout.secureserver.net
MAIL_PORT=80
MAIL_USERNAME=xxxxxxx
MAIL_PASSWORD=xxxxxxx
MAIL_ENCRYPTION=null


Now we are ready for make mailable class for this we have to go teminal and write following command.


php artisan make:mail SendMail


This command will make SendMail.php file inside App\Mail\SendMail.php. In this class we have to define one property with name $data, by using this property we can pass data at the time of create an new instance of this class.

App\Mail\SendMail.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendMail extends Mailable
{
    use Queueable, SerializesModels;
    public $data;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from('john@webslesson.info')->subject('New Customer Equiry')->view('dynamic_email_template')->with('data', $this->data);
    }
}

?>


In above source code we can see build() method, which build the message for send.
from() - This method is use to define from email address.
subject() - This method is use to define subject of an Email
view() - By using this view method we can fetch content from view file which has been put under email body.
with() - This is method is used to pass data into view file, so we can make dynamic email body content.

Step 6 - Make View file for Email Body


In this framework email body content has been get from view file. We below we have make one dynamic_email_template.blade.php view file under resources/views folder.

resources/views/dynamic_email_template.blade.php

<p>Hi, This is {{ $data['name'] }}</p>
<p>I have some query like {{ $data['message'] }}.</p>
<p>It would be appriciative, if you gone through this feedback.</p>


Above we can see in this file we have pass $data variable into this view file. Here we can see how we have pass $data['name'] and $data['message'] variable under this view file. So, this way we can make dynamic email body in Laravel for send email.

Step 7 - Make Send() under Controller


This is last step for send an email in Laravel and in step we have to make send method for handle form submit request for send an email.

app\Http\Controllers\SendEmailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;

class SendEmailController extends Controller
{
    function index()
    {
     return view('send_email');
    }

    function send(Request $request)
    {
     $this->validate($request, [
      'name'     =>  'required',
      'email'  =>  'required|email',
      'message' =>  'required'
     ]);

        $data = array(
            'name'      =>  $request->name,
            'message'   =>   $request->message
        );

     Mail::to('web-tutorial@programmer.net')->send(new SendMail($data));
     return back()->with('success', 'Thanks for contacting us!');

    }
}

?>


Here in this send() method first we have validate form data by using validate() method we can validate form data and if any data not follow validation rules it stop code execution and send validation message to view file.

But suppose all validation rules pass then this method process for send and email. So, here first we have store form data under $data variable. This variable has been pass into dynamic_email_tempate.php view file by using SendMail.php mailable class.

And lastly for send an email we have use Maill class and in this we have use to() in which we can define on which email address email must be received. After this for send an email we have use send() method. In this method we have create new instance of SendMail.php mailable class and in this instance we have pass $data variable value and this method will send an email.

After successfully email send url must be redirect to contact form again form this we have use back() method with success message which has been display above contact form.

Here How can we send an email in Laravel code is ready now we have to run Laravel application, for this we have to go to terminal and write following command.


php artisan serve


If you want to see video tutorial of this post, you can see above the start of post. If you have any query regarding of this tutorial, you can share query under comment box.

Wednesday, 19 September 2018

Add Server-side DataTables Custom Filter using PHP with Ajax



jQuery Datatables when initialized on the HTML table it has automatically make certain valuable feature like data pagination, table column sorting, search all table column data from single textbox, display number of records per page functionality without writing of any line of code or script. So, here we have to discuss how can we remove default DataTables search textbox and make custom serach of filter DataTables data using PHP script with Ajax. Because Default Search box is used for search records of all table column and display on Datatables. But in Web Development, Sometimes we want to required custom search filter for get specific column search onlu not whole table column search. For this in this tutorial, We will learn how can we implement custom search filter into jQuery DataTables by using Ajax with PHP script.

jQuery Datatables Customer Search filter with Server side processing help us to get records based on our choices of data filter. For example from the list of data we want to just filter "Male" gender data only. So we have search search in textbox then it will return female data also. For this we have to required custom search filter in Datatables for increase efficiency of exact search of data. We can implement custom search by using HTML Select box or even textbox also for filter jQuery Datatables data.







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;






database_connection.php



<?php

//database_connection.php

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

?>


index.php




<?php

include('database_connection.php');

$country = '';
$query = "SELECT DISTINCT Country FROM tbl_customer ORDER BY Country ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
 $country .= '<option value="'.$row['Country'].'">'.$row['Country'].'</option>';
}

?>

<html>
 <head>
  <title>Custom Search in jQuery Datatables using PHP Ajax</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://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.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">Custom Search in jQuery Datatables using PHP Ajax</h3>
   <br />
   <div class="row">
    <div class="col-md-4"></div>
    <div class="col-md-4">
     <div class="form-group">
      <select name="filter_gender" id="filter_gender" class="form-control" required>
       <option value="">Select Gender</option>
       <option value="Male">Male</option>
       <option value="Female">Female</option>
      </select>
     </div>
     <div class="form-group">
      <select name="filter_country" id="filter_country" class="form-control" required>
       <option value="">Select Country</option>
       <?php echo $country; ?>
      </select>
     </div>
     <div class="form-group" align="center">
      <button type="button" name="filter" id="filter" class="btn btn-info">Filter</button>
     </div>
    </div>
    <div class="col-md-4"></div>
   </div>
   <div class="table-responsive">
    <table id="customer_data" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th width="20%">Customer Name</th>
       <th width="10%">Gender</th>
       <th width="25%">Address</th>
       <th width="15%">City</th>
       <th width="15%">Postal Code</th>
       <th width="15%">Country</th>
      </tr>
     </thead>
    </table>
    <br />
    <br />
    <br />
   </div>
  </div>
 </body>
</html>

<script type="text/javascript" language="javascript" >
 $(document).ready(function(){
  
  fill_datatable();
  
  function fill_datatable(filter_gender = '', filter_country = '')
  {
   var dataTable = $('#customer_data').DataTable({
    "processing" : true,
    "serverSide" : true,
    "order" : [],
    "searching" : false,
    "ajax" : {
     url:"fetch.php",
     type:"POST",
     data:{
      filter_gender:filter_gender, filter_country:filter_country
     }
    }
   });
  }
  
  $('#filter').click(function(){
   var filter_gender = $('#filter_gender').val();
   var filter_country = $('#filter_country').val();
   if(filter_gender != '' && filter_country != '')
   {
    $('#customer_data').DataTable().destroy();
    fill_datatable(filter_gender, filter_country);
   }
   else
   {
    alert('Select Both filter option');
    $('#customer_data').DataTable().destroy();
    fill_datatable();
   }
  });
  
  
 });
 
</script>


fetch.php



<?php

include('database_connection.php');

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

$query = "
SELECT * FROM tbl_customer 
";

if(isset($_POST['filter_gender'], $_POST['filter_country']) && $_POST['filter_gender'] != '' && $_POST['filter_country'] != '')
{
 $query .= '
 WHERE Gender = "'.$_POST['filter_gender'].'" AND Country = "'.$_POST['filter_country'].'" 
 ';
}

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

?>

Saturday, 15 September 2018

Codeigniter - Detect User IP Browser Operating System Details



If you want to get or fetch or collect user information like who has visit your website, so you can do this things very easily if you have use Codeigniter. By using Codeigniter we can easily collect user information like user IP Address, browser details, browser version, operating system which he has use in his computer, we can also detect from which device he has get access our website etc. We can fetch all these user information by using Codeigniter "user_agent" library.

User Agent Library in Codeigniter is one class which help programmer to detect user information about user browser, mobile device or even robot visiting to website also. If you have use simple PHP script from get all these information then it is very difficult but in Codeigniter you have simple load this user_agent library and simple way to fetch all user information. Because we want know who has visit our website, from which region or location our website has been open. So, If any one has do any fraud on our website then we can easily detect particular user based on his information. So, it is required to get such type of user information and this task we can easily do by using Codeigniter User Agent Library.









Source Code


Controllers


application/controllers/UserDetails.php

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

class UserDetails extends CI_Controller {
 
 function index()
 {
  $this->load->library('user_agent');
  $data['browser'] = $this->agent->browser();
  $data['browser_version'] = $this->agent->version();
  $data['os'] = $this->agent->platform();
  $data['ip_address'] = $this->input->ip_address();
  $this->load->view('user_details', $data);
 }
 
}
?>


Views



<!DOCTYPE html>
<html>
<head>
 <title>How to Get User IP, Browser & OS Details 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">How to Get User IP, Browser & OS Details in Codeigniter</h3>
  <br />
  <div class="table-responsive">
   <table class="table table-bordered table-striped">
    <tr>
     <td><b>IP Address</b></td>
     <td><?php echo $ip_address; ?></td>
    </tr>
    <tr>
     <td><b>Operating System</b></td>
     <td><?php echo $os; ?></td>
    </tr>
    <tr>
     <td><b>Browser Details</b></td>
     <td><?php echo $browser . ' - ' . $browser_version; ?></td>
    </tr>
   </table>
  </div>
 </div>
</body>
</html>