Showing posts with label codeigniter tutorial. Show all posts
Showing posts with label codeigniter tutorial. Show all posts

Sunday, 2 December 2018

Ajax Codeigniter Product Filter with Pagination

Ajax Codeigniter Product Filter with Pagination - Part 1



Ajax Codeigniter Product Filter with Pagination - Part 2



Ajax Codeigniter Product Filter with Pagination - Part 3



Ajax Codeigniter Product Filter with Pagination - Part 4




This post is for Codeigniter web developer, because in this post we have make stylish product filter in Codeigniter framework by using Ajax jQuery. In this product filter user can filter product details by different filter which we have make by using Checkbox, and even product can be filter on two price range. For make price range filter here we have use jQuery UI slider plugin. This all operation has been done by using jQuery Ajax with Codeigniter framework.

In this Codeigniter ajax product filter we have also add pagination feature also. So, all product details will not be load on same page but it will be divided into different web page. So, it will reduce web page loading time. Here we have use Codeigniter pagination library for add pagination feature into Codeigniter product filter. If number of product load has been increase by limit to display on webpage, then in Codeigniter product filter it will automatically add pagination link. For go to one page to another page, here also we have use ajax also, so it will load another page product data without refresh of web page. So, this is Codeigniter product filter with pagination link using Ajax.


In most of the ecommerce website all product has been display with differnt product filter with pagination link. There are also for filter product data input type checkbox has been used for filter product data on different condition. Sameway for filter product data between two price, for this here also we have use jQuery UI library slider plugin. When we have slide price, and stop slide then it will fire ajax request for fetch data and display product data on web page which come between two price. These are basic functionality of Codeigniter Ajax Product filter with pagination feature. Below you can find complete source code of this tutorial.




Soruce Code


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `product_id` int(20) NOT NULL,
  `product_name` varchar(120) NOT NULL,
  `product_brand` varchar(100) NOT NULL,
  `product_price` decimal(8,2) NOT NULL,
  `product_ram` char(5) NOT NULL,
  `product_storage` varchar(50) NOT NULL,
  `product_camera` varchar(20) NOT NULL,
  `product_image` varchar(100) NOT NULL,
  `product_quantity` mediumint(5) NOT NULL,
  `product_status` enum('0','1') NOT NULL COMMENT '0-active,1-inactive'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`product_id`, `product_name`, `product_brand`, `product_price`, `product_ram`, `product_storage`, `product_camera`, `product_image`, `product_quantity`, `product_status`) VALUES
(1, 'Honor 9 Lite (Sapphire Blue, 64 GB)  (4 GB RAM)', 'Honor', '14499.00', '4', '64', '13', 'image-1.jpeg', 10, '1'),
(2, '\r\nInfinix Hot S3 (Sandstone Black, 32 GB)  (3 GB RAM)', 'Infinix', '8999.00', '3', '32', '13', 'image-2.jpeg', 10, '1'),
(3, 'VIVO V9 Youth (Gold, 32 GB)  (4 GB RAM)', 'VIVO', '16990.00', '4', '32', '16', 'image-3.jpeg', 10, '1'),
(4, 'Moto E4 Plus (Fine Gold, 32 GB)  (3 GB RAM)', 'Moto', '11499.00', '3', '32', '8', 'image-4.jpeg', 10, '1'),
(5, 'Lenovo K8 Plus (Venom Black, 32 GB)  (3 GB RAM)', 'Lenevo', '9999.00', '3', '32', '13', 'image-5.jpg', 10, '1'),
(6, 'Samsung Galaxy On Nxt (Gold, 16 GB)  (3 GB RAM)', 'Samsung', '10990.00', '3', '16', '13', 'image-6.jpeg', 10, '1'),
(7, 'Moto C Plus (Pearl White, 16 GB)  (2 GB RAM)', 'Moto', '7799.00', '2', '16', '8', 'image-7.jpeg', 10, '1'),
(8, 'Panasonic P77 (White, 16 GB)  (1 GB RAM)', 'Panasonic', '5999.00', '1', '16', '8', 'image-8.jpeg', 10, '1'),
(9, 'OPPO F5 (Black, 64 GB)  (6 GB RAM)', 'OPPO', '19990.00', '6', '64', '16', 'image-9.jpeg', 10, '1'),
(10, 'Honor 7A (Gold, 32 GB)  (3 GB RAM)', 'Honor', '8999.00', '3', '32', '13', 'image-10.jpeg', 10, '1'),
(11, 'Asus ZenFone 5Z (Midnight Blue, 64 GB)  (6 GB RAM)', 'Asus', '29999.00', '6', '128', '12', 'image-12.jpeg', 10, '1'),
(12, 'Redmi 5A (Gold, 32 GB)  (3 GB RAM)', 'MI', '5999.00', '3', '32', '13', 'image-12.jpeg', 10, '1'),
(13, 'Intex Indie 5 (Black, 16 GB)  (2 GB RAM)', 'Intex', '4999.00', '2', '16', '8', 'image-13.jpeg', 10, '1'),
(14, 'Google Pixel 2 XL (18:9 Display, 64 GB) White', 'Google', '61990.00', '4', '64', '12', 'image-14.jpeg', 10, '1'),
(15, 'Samsung Galaxy A9', 'Samsung', '36000.00', '8', '128', '24', 'image-15.jpeg', 10, '1'),
(16, 'Lenovo A5', 'Lenovo', '5999.00', '2', '16', '13', 'image-16.jpeg', 10, '1'),
(17, 'Asus Zenfone Lite L1', 'Asus', '5999.00', '2', '16', '13', 'image-17.jpeg', 10, '1'),
(18, 'Lenovo K9', 'Lenovo', '8999.00', '3', '32', '13', 'image-18.jpeg', 10, '1'),
(19, 'Infinix Hot S3x', 'Infinix', '9999.00', '3', '32', '13', 'image-19.jpeg', 10, '1'),
(20, 'Realme 2', 'Realme', '8990.00', '4', '64', '13', 'image-20.jpeg', 10, '1'),
(21, 'Redmi Note 6 Pro', 'Redmi', '13999.00', '4', '64', '20', 'image-21.jpeg', 10, '1'),
(22, 'Realme C1', 'Realme', '7999.00', '2', '16', '15', 'image-22.jpeg', 10, '1'),
(23, 'Vivo V11', 'Vivo', '22900.00', '6', '64', '21', 'image-23.jpeg', 10, '1'),
(24, 'Oppo F9 Pro', 'Oppo', '23990.00', '6', '64', '18', 'image-24.jpg', 10, '1'),
(25, 'Honor 9N', 'Honor', '11999.00', '4', '64', '15', 'image-25.jpg', 10, '1'),
(26, 'Redmi 6A', 'Redmi', '6599.00', '2', '16', '13', 'image-26.jpeg', 10, '1'),
(27, 'InFocus Vision 3', 'InFocus', '7399.00', '2', '16', '13', 'image-27.jpeg', 10, '1'),
(28, 'Vivo Y69', 'Vivo', '11390.00', '3', '32', '16', 'image-28.jpeg', 10, '1'),
(29, 'Honor 7x', 'Honor', '12721.00', '4', '32', '18', 'image-29.jpeg', 10, '1'),
(30, 'Nokia 2.1', 'Nokia', '6580.00', '2', '1', '8', 'image-30.jpeg', 10, '1');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `product`
--
ALTER TABLE `product`
  ADD PRIMARY KEY (`product_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
  MODIFY `product_id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31;




Controllers - Product_filter.php



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

class Product_filter extends CI_Controller {
 
 public function __construct()
 {
  parent::__construct();
  $this->load->model('product_filter_model');
 }

 function index()
 {
  $data['brand_data'] = $this->product_filter_model->fetch_filter_type('product_brand');
  $data['ram_data'] = $this->product_filter_model->fetch_filter_type('product_ram');
  $data['product_storage'] = $this->product_filter_model->fetch_filter_type('product_storage');
  $this->load->view('product_filter', $data);
 }

 function fetch_data()
 {
  sleep(1);
  $minimum_price = $this->input->post('minimum_price');
  $maximum_price = $this->input->post('maximum_price');
  $brand = $this->input->post('brand');
  $ram = $this->input->post('ram');
  $storage = $this->input->post('storage');
  $this->load->library('pagination');
  $config = array();
  $config['base_url'] = '#';
  $config['total_rows'] = $this->product_filter_model->count_all($minimum_price, $maximum_price, $brand, $ram, $storage);
  $config['per_page'] = 8;
  $config['uri_segment'] = 3;
  $config['use_page_numbers'] = TRUE;
  $config['full_tag_open'] = '<ul class="pagination">';
  $config['full_tag_close'] = '</ul>';
  $config['first_tag_open'] = '<li>';
  $config['first_tag_close'] = '</li>';
  $config['last_tag_open'] = '<li>';
  $config['last_tag_close'] = '</li>';
  $config['next_link'] = '&gt;';
  $config['next_tag_open'] = '<li>';
  $config['next_tag_close'] = '</li>';
  $config['prev_link'] = '&lt;';
  $config['prev_tag_open'] = '<li>';
  $config['prev_tag_close'] = '</li>';
  $config['cur_tag_open'] = "<li class='active'><a href='#'>";
  $config['cur_tag_close'] = '</a></li>';
  $config['num_tag_open'] = '<li>';
  $config['num_tag_close'] = '</li>';
  $config['num_links'] = 3;
  $this->pagination->initialize($config);
  $page = $this->uri->segment(3);
  $start = ($page - 1) * $config['per_page'];
  $output = array(
   'pagination_link'  => $this->pagination->create_links(),
   'product_list'   => $this->product_filter_model->fetch_data($config["per_page"], $start, $minimum_price, $maximum_price, $brand, $ram, $storage)
  );
  echo json_encode($output);
 }
  
}
?>


Models - Product_filter_model.php



<?php

class Product_filter_model extends CI_Model
{
 function fetch_filter_type($type)
 {
  $this->db->distinct();
  $this->db->select($type);
  $this->db->from('product');
  $this->db->where('product_status', '1');
  return $this->db->get();
 }

 function make_query($minimum_price, $maximum_price, $brand, $ram, $storage)
 {
  $query = "
  SELECT * FROM product 
  WHERE product_status = '1' 
  ";

  if(isset($minimum_price, $maximum_price) && !empty($minimum_price) &&  !empty($maximum_price))
  {
   $query .= "
    AND product_price BETWEEN '".$minimum_price."' AND '".$maximum_price."'
   ";
  }

  if(isset($brand))
  {
   $brand_filter = implode("','", $brand);
   $query .= "
    AND product_brand IN('".$brand_filter."')
   ";
  }

  if(isset($ram))
  {
   $ram_filter = implode("','", $ram);
   $query .= "
    AND product_ram IN('".$ram_filter."')
   ";
  }

  if(isset($storage))
  {
   $storage_filter = implode("','", $storage);
   $query .= "
    AND product_storage IN('".$storage_filter."')
   ";
  }
  return $query;
 }

 function count_all($minimum_price, $maximum_price, $brand, $ram, $storage)
 {
  $query = $this->make_query($minimum_price, $maximum_price, $brand, $ram, $storage);
  $data = $this->db->query($query);
  return $data->num_rows();
 }

 function fetch_data($limit, $start, $minimum_price, $maximum_price, $brand, $ram, $storage)
 {
  $query = $this->make_query($minimum_price, $maximum_price, $brand, $ram, $storage);

  $query .= ' LIMIT '.$start.', ' . $limit;

  $data = $this->db->query($query);

  $output = '';
  if($data->num_rows() > 0)
  {
   foreach($data->result_array() as $row)
   {
    $output .= '
    <div class="col-sm-4 col-lg-3 col-md-3">
     <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:450px;">
      <img src="'.base_url().'images/'. $row['product_image'] .'" alt="" class="img-responsive" >
      <p align="center"><strong><a href="#">'. $row['product_name'] .'</a></strong></p>
      <h4 style="text-align:center;" class="text-danger" >'. $row['product_price'] .'</h4>
      <p>Camera : '. $row['product_camera'].' MP<br />
      Brand : '. $row['product_brand'] .' <br />
      RAM : '. $row['product_ram'] .' GB<br />
      Storage : '. $row['product_storage'] .' GB </p>
     </div>
    </div>
    ';
   }
  }
  else
  {
   $output = '<h3>No Data Found</h3>';
  }
  return $output;
 }
}

?>




Views - product_filter.php



<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Product Filters in Codeigniter using Ajax</title>

    <!-- Bootstrap Core CSS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <link href = "<?php echo base_url(); ?>asset/jquery-ui.css" rel = "stylesheet">
    <!-- Custom CSS -->
    <link href="<?php echo base_url(); ?>asset/style.css" rel="stylesheet">
</head>

<body>
    <!-- Page Content -->
    <div class="container">
        <div class="row">
            <div class="col-md-3">
    <br />
    <br />
    <br />
    <div class="list-group">
     <h3>Price</h3>
     <input type="hidden" id="hidden_minimum_price" value="0" />
                    <input type="hidden" id="hidden_maximum_price" value="65000" />
                    <p id="price_show">1000 - 65000</p>
                    <div id="price_range"></div>
                </div>    
                <div class="list-group">
     <h3>Brand</h3>
     <?php
                    foreach($brand_data->result_array() as $row)
                    {
                    ?>
                    <div class="list-group-item checkbox">
                        <label><input type="checkbox" class="common_selector brand" value="<?php echo $row['product_brand']; ?>"  > <?php echo $row['product_brand']; ?></label>
                    </div>
                    <?php
                    }
                    ?>
                </div>

    <div class="list-group">
     <h3>RAM</h3>
     <?php
                    foreach($ram_data->result_array() as $row)
                    {
                    ?>
                    <div class="list-group-item checkbox">
                        <label><input type="checkbox" class="common_selector ram" value="<?php echo $row['product_ram']; ?>" > <?php echo $row['product_ram']; ?> GB</label>
                    </div>
                    <?php
                    }
                    ?> 
                </div>
    
    <div class="list-group">
     <h3>Internal Storage</h3>
     <?php
                    foreach($product_storage->result_array() as $row)
                    {
                    ?>
                    <div class="list-group-item checkbox">
                        <label><input type="checkbox" class="common_selector storage" value="<?php echo $row['product_storage']; ?>"  > <?php echo $row['product_storage']; ?> GB</label>
                    </div>
                    <?php
                    }
                    ?> 
                </div>
            </div>

            <div class="col-md-9">
             <h2 align="center">Product Filters in Codeigniter using Ajax</h2>
    <br />
    <div align="center" id="pagination_link">

                </div>
    <br />
    <br />
    <br />
                <div class="row filter_data">

                </div>
            </div>
        </div>

    </div>
<style>
#loading
{
 text-align:center; 
 background: url('<?php echo base_url(); ?>asset/loader.gif') no-repeat center; 
 height: 150px;
}
</style>

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

    filter_data(1);

    function filter_data(page)
    {
        $('.filter_data').html('<div id="loading" style="" ></div>');
        var action = 'fetch_data';
        var minimum_price = $('#hidden_minimum_price').val();
        var maximum_price = $('#hidden_maximum_price').val();
        var brand = get_filter('brand');
        var ram = get_filter('ram');
        var storage = get_filter('storage');
        $.ajax({
            url:"<?php echo base_url(); ?>product_filter/fetch_data/"+page,
            method:"POST",
            dataType:"JSON",
            data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, ram:ram, storage:storage},
            success:function(data)
            {
                $('.filter_data').html(data.product_list);
                $('#pagination_link').html(data.pagination_link);
            }
        })
    }

    function get_filter(class_name)
    {
        var filter = [];
        $('.'+class_name+':checked').each(function(){
            filter.push($(this).val());
        });
        return filter;
    }

    $(document).on('click', '.pagination li a', function(event){
        event.preventDefault();
        var page = $(this).data('ci-pagination-page');
        filter_data(page);
    });

    $('.common_selector').click(function(){
        filter_data(1);
    });

    $('#price_range').slider({
        range:true,
        min:1000,
        max:65000,
        values:[1000,65000],
        step:500,
        stop:function(event, ui)
        {
            $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
            $('#hidden_minimum_price').val(ui.values[0]);
            $('#hidden_maximum_price').val(ui.values[1]);
            filter_data(1);
        }

    });

});
</script>

</body>

</html>

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.




Saturday, 28 April 2018

Codeigniter PDF Generation using Dompdf


We all know PDF document is the extremely helpful type for make web document in any website. This type of file give us a very simple and user interface friendly style for download large amount of data in single file. If we want to download web data, then first we want to convert that data from HTML to PDF format. So, if we want to make conversion from HTML to PDF format, for this we have to use PHP Library.

PHP has one Dompdf library which can make PDF file from HTML content. By using this library it is very simple to generate PDF file from HTML content in PHP script using Dompdf library. But if you have use Codeigniter framework for web development, So there is somethings different process for generate PDF file using Dompdf in Codeigniter. Here in this post we have disccuss how to convert HTML content to PDF format file or generate PDF file in codeigniter by using Dompdf.

Dompdf library provides us to simplest way to generate PDF from HTML in Codeigniter. Here this example will show you how to configure Dompdf library in Codeigniter. Here we will make Codeigniter PDF library by using this Dompdf library and after this we can use Codeigniter library as we have use other in build Codeigniter library. In this Customer PDF library we can use all the available feature of Dompdf library class which we can use in our customer Codeigniter PDF library. Below example we have generates dynamic PDF file from dynamic HTML content. So by using this code we can generate dynamic PDF files from any dynamic HTML data as per our requirement.






Source Code


application/controllers/HtmltoPDF.php



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

class HtmltoPDF extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('htmltopdf_model');
  $this->load->library('pdf');
 }

 public function index()
 {
  $data['customer_data'] = $this->htmltopdf_model->fetch();
  $this->load->view('htmltopdf', $data);
 }

 public function details()
 {
  if($this->uri->segment(3))
  {
   $customer_id = $this->uri->segment(3);
   $data['customer_details'] = $this->htmltopdf_model->fetch_single_details($customer_id);
   $this->load->view('htmltopdf', $data);
  }
 }

 public function pdfdetails()
 {
  if($this->uri->segment(3))
  {
   $customer_id = $this->uri->segment(3);
   $html_content = '<h3 align="center">Convert HTML to PDF in CodeIgniter using Dompdf</h3>';
   $html_content .= $this->htmltopdf_model->fetch_single_details($customer_id);
   $this->pdf->loadHtml($html_content);
   $this->pdf->render();
   $this->pdf->stream("".$customer_id.".pdf", array("Attachment"=>0));
  }
 }

}

?>



application/models/Htmltopdf_model.php



<?php
class Htmltopdf_model extends CI_Model
{
 function fetch()
 {
  $this->db->order_by('CustomerID', 'DESC');
  return $this->db->get('tbl_customer');
 }
 function fetch_single_details($customer_id)
 {
  $this->db->where('CustomerID', $customer_id);
  $data = $this->db->get('tbl_customer');
  $output = '<table width="100%" cellspacing="5" cellpadding="5">';
  foreach($data->result() as $row)
  {
   $output .= '
   <tr>
    <td width="25%"><img src="'.base_url().'images/'.$row->images.'" /></td>
    <td width="75%">
     <p><b>Name : </b>'.$row->CustomerName.'</p>
     <p><b>Address : </b>'.$row->Address.'</p>
     <p><b>City : </b>'.$row->City.'</p>
     <p><b>Postal Code : </b>'.$row->PostalCode.'</p>
     <p><b>Country : </b> '.$row->Country.' </p>
    </td>
   </tr>
   ';
  }
  $output .= '
  <tr>
   <td colspan="2" align="center"><a href="'.base_url().'htmltopdf" class="btn btn-primary">Back</a></td>
  </tr>
  ';
  $output .= '</table>';
  return $output;
 }
}

?>


application/views/htmltopdf.php



<html>
<head>
    <title>Convert HTML to PDF in CodeIgniter using Dompdf</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 box">
  <br />
  <h3 align="center">Convert HTML to PDF in CodeIgniter using Dompdf</h3>
  <br />
  <?php
  if(isset($customer_data))
  {
  ?>
  <div class="table-responsive">
   <table class="table table-striped table-bordered">
    <tr>
     <th>Customer ID</th>
     <th>Customer Name</th>
     <th>View</th>
     <th>View in PDF</th>
    </tr>
   <?php
   foreach($customer_data->result() as $row)
   {
    echo '
    <tr>
     <td>'.$row->CustomerID.'</td>
     <td>'.$row->CustomerName.'</td>
     <td><a href="'.base_url().'htmltopdf/details/'.$row->CustomerID.'">View</a></td>
     <td><a href="'.base_url().'htmltopdf/pdfdetails/'.$row->CustomerID.'">View in PDF</a></td>
    </tr>
    ';
   }
   ?>
   </table>
  </div>
  <?php
  }
  if(isset($customer_details))
  {
   echo $customer_details;
  }
  ?>
 </div>
</body>
</html>


application/libraries/Pdf.php



<?php 
if (!defined('BASEPATH')) exit('No direct script access allowed');  
 
require_once 'dompdf/autoload.inc.php';

use Dompdf\Dompdf;

class Pdf extends Dompdf
{
 public function __construct()
 {
   parent::__construct();
 } 
}

?>