Sunday, 12 August 2018

Create Dynamic PDF & Send as Attachment with Email in PHP

If you are trying to create dynamic pdf file from mysql database and then after you want to send that dynamically generated pdf file as attachment with email, this is a very common feature in most of enterprise level web application. Because if any large web application then we have to send email with dynamically generated pdf file for providing such type of data information. So, in this post we have conver this topic in which we have learn how can we create dynamic pdf file from mysql database by using domPDF library and then after we will send that dynamically created pdf file will send as attachment with email using PHPMailer in PHP script. So, here we have learn PHP send email with PDF attachment.

In this tutorial, we will describe you how to fetch data from Mysql database and create PDF from that data and then after attach that PDF file to an HTML email and lastly send it. Here we have use domPDF for PDF generation and PHPMailer for sending email.

After searching on internet regarding how to create PDF file in PHP, so after searching we have found dompdf library which is the best library for create PDF file from HTML. This library simply convert HTML code of any web page and converts it to a PDF. And for sending email we have found PHPMailer library, this library has been easy to use and it can send HTML email with file attachment. So, by using both library we have make our task like create dynamic pdf file and send email as attachment.

Before learning this topic, in your mind will generate one question how to generate pdf file and then after it will be send as attachment, so here we will be creating PDF file temporary by using domPDF library which a library which has convert HTML info PDF file and then after by using PHPMailer which has been used for send email in our PHP script and after sending of email with attached PDF file, that file will be removed from folder. So, this is whole process of creating PDF file and sending email with attachment in PHP script using Dompdf and PHPMailer library.










Source Code


index.php



<?php

//index.php

$message = '';

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

function fetch_customer_data($connect)
{
 $query = "SELECT * FROM tbl_customer";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '
 <div class="table-responsive">
  <table class="table table-striped table-bordered">
   <tr>
    <th>Name</th>
    <th>Address</th>
    <th>City</th>
    <th>Postal Code</th>
    <th>Country</th>
   </tr>
 ';
 foreach($result as $row)
 {
  $output .= '
   <tr>
    <td>'.$row["CustomerName"].'</td>
    <td>'.$row["Address"].'</td>
    <td>'.$row["City"].'</td>
    <td>'.$row["PostalCode"].'</td>
    <td>'.$row["Country"].'</td>
   </tr>
  ';
 }
 $output .= '
  </table>
 </div>
 ';
 return $output;
}

if(isset($_POST["action"]))
{
 include('pdf.php');
 $file_name = md5(rand()) . '.pdf';
 $html_code = '<link rel="stylesheet" href="bootstrap.min.css">';
 $html_code .= fetch_customer_data($connect);
 $pdf = new Pdf();
 $pdf->load_html($html_code);
 $pdf->render();
 $file = $pdf->output();
 file_put_contents($file_name, $file);
 
 require 'class/class.phpmailer.php';
 $mail = new PHPMailer;
 $mail->IsSMTP();        //Sets Mailer to send message using SMTP
 $mail->Host = 'smtpout.secureserver.net';  //Sets the SMTP hosts of your Email hosting, this for Godaddy
 $mail->Port = '80';        //Sets the default SMTP server port
 $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
 $mail->Username = 'xxxxxxxxxx';     //Sets SMTP username
 $mail->Password = 'xxxxxxxxxx';     //Sets SMTP password
 $mail->SMTPSecure = '';       //Sets connection prefix. Options are "", "ssl" or "tls"
 $mail->From = 'info@webslesson.info';   //Sets the From email address for the message
 $mail->FromName = 'Webslesson.info';   //Sets the From name of the message
 $mail->AddAddress('web-tutorial@programmer.net', 'Name');  //Adds a "To" address
 $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
 $mail->IsHTML(true);       //Sets message type to HTML    
 $mail->AddAttachment($file_name);         //Adds an attachment from a path on the filesystem
 $mail->Subject = 'Customer Details';   //Sets the Subject of the message
 $mail->Body = 'Please Find Customer details in attach PDF File.';    //An HTML or plain text message body
 if($mail->Send())        //Send an Email. Return true on success or false on error
 {
  $message = '<label class="text-success">Customer Details has been send successfully...</label>';
 }
 unlink($file_name);
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Create Dynamic PDF Send As Attachment with Email in PHP</title>
  <script src="jquery.min.js"></script>
  <link rel="stylesheet" href="bootstrap.min.css" />
  <script src="bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Create Dynamic PDF Send As Attachment with Email in PHP</h3>
   <br />
   <form method="post">
    <input type="submit" name="action" class="btn btn-danger" value="PDF Send" /><?php echo $message; ?>
   </form>
   <br />
   <?php
   echo fetch_customer_data($connect);
   ?>   
  </div>
  <br />
  <br />
 </body>
</html>


pdf.php



<?php

//pdf.php

require_once 'dompdf/autoload.inc.php';

use Dompdf\Dompdf;

class Pdf extends Dompdf{

 public function __construct(){
  parent::__construct();
 }
}

?>






Friday, 10 August 2018

How to Make Product Filter in php using Ajax



Most of the e-commerce websites provide nice UI for filter product on their website by using different type of search filter like price range product filter and checkbox search filter. This type of product search filter with price range filter and checkbox product filter feature we have discuss here by using Ajax with PHP. In this post we will describe you how to search a product from list of product by using Ajax JQuery PHP and Mysql. Here we have developed product filter which are similar to largest e-commerce website. They have use this type of search filter for filter product on their website, so user can easily filter product on different category search filter. If user has select any price range then in this feature it will filter product which has been covered between that price range and same way if user want to find particular brand product which has come between that price range then user can also select brand then it will live display all product which relate to particular brand.

This tutorial is based on live filter of product using Ajax which has been used most of the ecommerce website. If you have visit any ecommerce website for buying product then you have first prefer price and in that price we want to get particular brand then you have to find particular product then you can easily filter from list of product on web page without refresh of web page. Here we have get result by using Ajax Jquery with PHP and Mysql. For make this type of functionality for our web application we have use Jquery UI slider plugin for filter product on price and HTML Checkbox input field for filter product on different category like brand etc. If user select particular condition and that condition will match with data available in database then that product will be display using PHP with Ajax. And if user clear filter then it will seen all product on web page. Below you can find complete source code of Ajax PHP Product filter.












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

--
-- 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=15;


database_connection.php



<?php 

//database_connection.php

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

?>


index.php



<?php 

//index.php

include('database_connection.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 filter in php</title>

    <script src="js/jquery-1.10.2.min.js"></script>
    <script src="js/jquery-ui.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link href = "css/jquery-ui.css" rel = "stylesheet">
    <!-- Custom CSS -->
    <link href="css/style.css" rel="stylesheet">
</head>

<body>
    <!-- Page Content -->
    <div class="container">
        <div class="row">
         <br />
         <h2 align="center">Advance Ajax Product Filters in PHP</h2>
         <br />
            <div class="col-md-3">                    
    <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>
                    <div style="height: 180px; overflow-y: auto; overflow-x: hidden;">
     <?php

                    $query = "SELECT DISTINCT(product_brand) FROM product WHERE product_status = '1' ORDER BY product_id DESC";
                    $statement = $connect->prepare($query);
                    $statement->execute();
                    $result = $statement->fetchAll();
                    foreach($result 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>

    <div class="list-group">
     <h3>RAM</h3>
                    <?php

                    $query = "
                    SELECT DISTINCT(product_ram) FROM product WHERE product_status = '1' ORDER BY product_ram DESC
                    ";
                    $statement = $connect->prepare($query);
                    $statement->execute();
                    $result = $statement->fetchAll();
                    foreach($result 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
                    $query = "
                    SELECT DISTINCT(product_storage) FROM product WHERE product_status = '1' ORDER BY product_storage DESC
                    ";
                    $statement = $connect->prepare($query);
                    $statement->execute();
                    $result = $statement->fetchAll();
                    foreach($result 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">
             <br />
                <div class="row filter_data">

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

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

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

    filter_data();

    function filter_data()
    {
        $('.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:"fetch_data.php",
            method:"POST",
            data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, ram:ram, storage:storage},
            success:function(data){
                $('.filter_data').html(data);
            }
        });
    }

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

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

    $('#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();
        }
    });

});
</script>

</body>

</html>


fetch_data.php



<?php

//fetch_data.php

include('database_connection.php');

if(isset($_POST["action"]))
{
 $query = "
  SELECT * FROM product WHERE product_status = '1'
 ";
 if(isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"]))
 {
  $query .= "
   AND product_price BETWEEN '".$_POST["minimum_price"]."' AND '".$_POST["maximum_price"]."'
  ";
 }
 if(isset($_POST["brand"]))
 {
  $brand_filter = implode("','", $_POST["brand"]);
  $query .= "
   AND product_brand IN('".$brand_filter."')
  ";
 }
 if(isset($_POST["ram"]))
 {
  $ram_filter = implode("','", $_POST["ram"]);
  $query .= "
   AND product_ram IN('".$ram_filter."')
  ";
 }
 if(isset($_POST["storage"]))
 {
  $storage_filter = implode("','", $_POST["storage"]);
  $query .= "
   AND product_storage IN('".$storage_filter."')
  ";
 }

 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $total_row = $statement->rowCount();
 $output = '';
 if($total_row > 0)
 {
  foreach($result 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="image/'. $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>';
 }
 echo $output;
}

?>







Top 5 PHP Development Frameworks That Speed Up Development



PHP or Hypertext Preprocessor is easily the most widely used programming language in the world. A server-side scripting language and embedded in HTML, it is ideal for developing dynamic websites and web-based applications. This open-source and efficient language has, over the years, grown to become a perfect alternative to other web development technologies. It is not only compatible with every web server but also works with frameworks and runs on a web server.

Although PHP is been stable, secure and user-fetidly, it has custom codes for every single functionality which ultimately paved the ways for frameworks. This is how it becomes possible to speed up web development and get the benefit of scalability. And yes, framework-based apps and solutions offer more security than regular products. For that reason, it makes to choose the right framework and add a new dimension to your web development.

Here are 5 top PHP development frameworks that speed-up development -

1. Laravel


Any mention of PHP frameworks is incomplete with Laravel which easily tops the popularity list among them all. This open-source framework is relatively new to the club yet helps deliver speed without having to increase project overheads. And yes, it leads the domain when it comes to delivering performance and scalability. Some of its major features include New directory structure, Route caching, Authentication and Multiple file system. And don’t forget, its ecosystem comes with the features of instant hosting and deployment platform to expediate development.

2. Symfony


Do you know what makes Symfony the first choice for web programmers? Yes, it comes with a highly flexible architecture that often sways website owners towards it. This free open-source framework, which is based on Model View Controller, it written in PHP programming language, and delivers compatibility with various databases including MySQL, Microsoft SQL server, Oracle and PostgreSQL. This framework stands out for being ideal for developing large-scaled enterprise projects. And yes, its huge ecosystem also has an active community of developers for help with any technical issues.

3. Yii 2


Yii is still there and yes, it’s easily among the oldest PHP frameworks for efficient web development. Now, it latest version – Yii 2 – is there to boost its already established popularity. One of reasons behind its success is its being a purely object-oriented framework. Needless to say, it’s faster than the others because it uses a perfect loading technique. You can integrate it with AJAX and jQuery features which helps make it fit for large-scale web development.

4. CakePHP


CakePHP always takes a prime spot on the list of PHP framework. It’s there for over a decade now, enjoys trust and appreciation. And yes, it continues to be popular for web development. There is no match yet for its speed, security and reliability. Its features have always been widely admired and they are not going to lose their shine soon. Apart from good documentation, its topmost features include SQL injection prevention, cross-site scripting (XSS) prevention and clean MVC Conventions. Developers and programmers simply love this framework and they can’t get more of it, ever.

5. Zend


Even if the Zend framework is that not that easy to learn, this does not take away anything from its usability and popularity. This open source and object-oriented web application framework packs in a range of features that help speed up web development. With that, you can easily promote web development best practices and add value to your web projects. You can also avail php development services India and ensure top-class and fully-functional websites and apps for yourself. This is how your business’ overall productivity can take a big jump easily.

Thursday, 2 August 2018

Ajax File Upload with Progress Bar using PHP JQuery

Upload of Image or File must always required a Progress bar. This type of website feature which has been ignored by most of the web developers. This type of feature is an one part of web application functionality. If we have not use progress bar in image or file upload using Ajax then user cannot seen what is uploading which we have done in back end and he cannot get idea about file or image has been uploaded or not.

So, if user has send request to server for upload file or image operation, then it is best practice to see them about the progress of their uploading. Display of uploading process in progress bar, it is a good sign of our website UI/UX. For improving our web application UI/UX then we have to display upload process in progress bar and user can get idea about upload operation in process or has been completed. We have already publish how to upload Image using Ajax with PHP, but there is only we have simply upload image to folder without displaying of upload process in progress bar. But in this post we have learn how can we create animated progress bar using Jquery with Bootstrap while uploading of an image via Ajax.

For Select Image or File from our local computer here we have use A file input html tag and after this we have send this file to PHP using Ajax. Once it has send file upload request to PHP, then in Ajax script will execute Jquery animation using animate() method and display file uploading process in progress bar which has been make by using Bootstrap. Bootstrap progress bar will display process of uploading using JQuery animation. Here we have also use Jquery Form plugin has been used for handle upload Image via Ajax with progress bar.










Image / File Upload HTML Form


On index.php page we have make one HTML form with Input file tag. So user can select file from their local computer and send file data by sending form using Ajax. For send form data in this page we have already included Jquery Form plugin at the starting of script. We have use HTML 5 file accept attribute for select only .jpg and .png file.


<!DOCTYPE html>
 <html>
 <head>
  <title></title>
  <link href="css/bootstrap.min.css" rel="stylesheet" />
  <script src="js/jquery-1.10.2.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/jquery.form.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Ajax File Upload Progress Bar using PHP JQuery</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading"><b>Ajax File Upload Progress Bar using PHP JQuery</b></div>
    <div class="panel-body">
     <form id="uploadImage" action="upload.php" method="post">
      <div class="form-group">
       <label>File Upload</label>
       <input type="file" name="uploadFile" id="uploadFile" accept=".jpg, .png" />
      </div>
      <div class="form-group">
       <input type="submit" id="uploadSubmit" value="Upload" class="btn btn-info" />
      </div>
      <div class="progress">
       <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
      </div>
      <div id="targetLayer" style="display:none;"></div>
     </form>
     <div id="loader-icon" style="display:none;"><img src="loader.gif" /></div>
    </div>
   </div>
  </div>
 </body>
</html>


JQuery Progress bar with Ajax Form Submit


In this example we have use Jquery Form library for submit form data using Ajax with JQuery Bootstrap animated progress bar. The ajaxSubmit() function has been used for submit image file to the PHP script via Ajax. Image Upload progress has been display in progress bar using uploadProgress callback function and by using Jquery animate() method we have use for display upload progress in progress bar.


<script>
$(document).ready(function(){
 $('#uploadImage').submit(function(event){
  if($('#uploadFile').val())
  {
   event.preventDefault();
   $('#loader-icon').show();
   $('#targetLayer').hide();
   $(this).ajaxSubmit({
    target: '#targetLayer',
    beforeSubmit:function(){
     $('.progress-bar').width('50%');
    },
    uploadProgress: function(event, position, total, percentageComplete)
    {
     $('.progress-bar').animate({
      width: percentageComplete + '%'
     }, {
      duration: 1000
     });
    },
    success:function(){
     $('#loader-icon').hide();
     $('#targetLayer').show();
    },
    resetForm: true
   });
  }
  return false;
 });
});
</script>


PHP Code for File Upload


This is simple PHP file upload script for upload file in specified location folder. Here All file data has been stored into $_FILES superglobal variable of PHP. For upload file to specified upload folder we have use PHP move_uploaded_file() function.


<?php

//upload.php

if(!empty($_FILES))
{
 if(is_uploaded_file($_FILES['uploadFile']['tmp_name']))
 {
  sleep(1);
  $source_path = $_FILES['uploadFile']['tmp_name'];
  $target_path = 'upload/' . $_FILES['uploadFile']['name'];
  if(move_uploaded_file($source_path, $target_path))
  {
   echo '<img src="'.$target_path.'" class="img-thumbnail" width="300" height="250" />';
  }
 }
}

?>


If you have follow this source code then you can make Ajax Image upload with Progress bar in PHP script. If you want to download source code click on below link.





Monday, 30 July 2018

How to Convert Google Chart to PDF using PHP



If you have work on any PHP based dynamic web application and in which you are using Google Chart Library for creating report and visualization of your web application data then if you want to add one more feature like make PNG Image file or PDF file from your Dynamic Google chart which you have make by fetch data from Mysql database using PHP PDO script. So here you can find step by step guide how can we easily export Google chart in PDF file format or PNG Image. We have publish many post in this site regarding how to make dynamic chart by using Google Chart with PHP script with Mysql database.

For creating or exporting Google chart to PDF file first we want to convert into PNG image. So, first we need to save Google Chart as PNG Image then after we can easily export or convert into PDF file using PHP. Here we have use DomPDF library for export Google chart to PDF using PHP.









Convert Google Chart into PNG


In below you can find source code of Creating of Dynamic Pie Chart from fetch data from Mysql database and based on data we have make Pie chart using Google Chart Library with PHP. Here we have use getImageURI() method which print Google chart as PNG Image on web page.


<?php  

//index.php

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

$query = "SELECT gender, count(*) as number FROM tbl_employee GROUP BY gender";

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

$statement->execute();

$result = $statement->fetchAll();

?>  
<!DOCTYPE html>  
<html>  
    <head>  
        <title>Export Google Chart to PDF using PHP with DomPDF</title>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>  
        <script type="text/javascript">
   google.charts.load('current', {'packages':['corechart']});

   google.charts.setOnLoadCallback(drawChart);

   function drawChart()
   {
    var data = google.visualization.arrayToDataTable([
     ['Gender', 'Number'],
     <?php
     foreach($result as $row)
     {
      echo "['".$row["gender"]."', ".$row["number"]."],";
     }
     ?>
    ]);

    var options = {
     title : 'Percentage of Male and Female Employee',
     pieHole : 0.4,
     chartArea:{left:100,top:70,width:'100%',height:'80%'}
    };
    var chart_area = document.getElementById('piechart');
    var chart = new google.visualization.PieChart(chart_area);

    google.visualization.events.addListener(chart, 'ready', function(){
     chart_area.innerHTML = '<img src="' + chart.getImageURI() + '" class="img-responsive">';
    });
    chart.draw(data, options);
   }

        </script>  
    </head>  
    <body>  
        <br /><br />  
        <div class="container" id="testing">  
            <h3 align="center">Export Google Chart to PDF using PHP with DomPDF</h3>  
            <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Export Google Chart to PDF using PHP with DomPDF</h3>
    </div>
    <div class="panel-body" align="center">
     <div id="piechart" style="width: 100%; max-width:900px; height: 500px; "></div>
    </div>
   </div>
        </div>
  <br />
  <div align="center">
   <form method="post" id="make_pdf" action="create_pdf.php">
    <input type="hidden" name="hidden_html" id="hidden_html" />
    <button type="button" name="create_pdf" id="create_pdf" class="btn btn-danger btn-xs">Make PDF</button>
   </form>
  </div>
  <br />
  <br />
  <br />
    </body>  
</html>

<script>
$(document).ready(function(){
 $('#create_pdf').click(function(){
  $('#hidden_html').val($('#testing').html());
  $('#make_pdf').submit();
 });
});
</script>


Export Image to PDF


After create PNG image from Google Chart, now we can easily export it to PDF file. There are different ways for convert PNG to PDF using PHP. For example make PDF file from HTML we have use different PHP Library like TCPDF or DOMPDF. But here we have use DOMPDF library in which we can also use Bootstrap CSS library also which steps you can find below.

1. First Download the latest version of DOMPDF Library from here.

2. Unzip DOMPDF library file and put into your working folder from where you have execute php script.

3. Make a HTML form which send action to PHP file which convert HTML code to PDF. Here we have send request to create_pdf.php.


<form method="post" id="make_pdf" action="create_pdf.php">
    <input type="hidden" name="hidden_html" id="hidden_html" />
    <button type="button" name="create_pdf" id="create_pdf" class="btn btn-danger btn-xs">Make PDF</button>
   </form>


Below you can find PHP Source code of pdf.php and create_pdf.php file for convert HTML to PDF.


<?php

//pdf.php

require_once 'dompdf/autoload.inc.php';

use Dompdf\Dompdf;

class Pdf extends Dompdf{

 public function __construct(){
  parent::__construct();
 }
}

?>



<?php

//create_pdf.php


include('pdf.php');

if(isset($_POST["hidden_html"]) && $_POST["hidden_html"] != '')
{
 $file_name = 'google_chart.pdf';
 $html = '<link rel="stylesheet" href="bootstrap.min.css">';
 $html .= $_POST["hidden_html"];

 $pdf = new Pdf();
 $pdf->load_html($html);
 $pdf->render();
 $pdf->stream($file_name, array("Attachment" => false));
}

?>


So, this is complete and step by step source code of Exporting of Google Chart to PDF using PHP PDO script with DOMPDF Library.

Database



--
-- Database: `testing`
--

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

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

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

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

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`) VALUES
(1, 'Bruce Tom', '656 Edsel Road\r\nSherman Oaks, CA 91403', 'Male', 'Driver', 36),
(5, 'Clara Gilliam', '63 Woodridge Lane\r\nMemphis, TN 38138', 'Female', 'Programmer', 24),
(6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26),
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 32),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29),
(175, 'Ronald D. Colella', '1571 Bingamon Branch Road, Barrington, IL 60010', 'Male', 'Top executive', 32),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 38),
(161, 'Glenda J. Stewart', '3482 Pursglove Court, Rossburg, OH 45362', 'Female', 'Cost consultant', 28),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 64),
(163, 'William C. Wright', '2653 Pyramid Valley Road, Cedar Rapids, IA 52404', 'Male', 'Political geographer', 33),
(178, 'Sara K. Ebert', '1197 Nelm Street\r\nMc Lean, VA 22102', 'Female', 'Billing machine operator', 50),
(177, 'Patricia L. Scott', '1584 Dennison Street\r\nModesto, CA 95354', 'Female', 'Urban and regional planner', 54),
(179, 'James K. Ridgway', '3462 Jody Road\r\nWayne, PA 19088', 'Female', 'Recreation leader', 41),
(180, 'Stephen A. Crook', '448 Deercove Drive\r\nDallas, TX 75201', 'Male', 'Optical goods worker', 36),
(181, 'Kimberly J. Ellis', '4905 Holt Street\r\nFort Lauderdale, FL 33301', 'Male', 'Dressing room attendant', 24),
(182, 'Elizabeth N. Bradley', '1399 Randall Drive\r\nHonolulu, HI 96819', 'Female', ' Software quality assurance analyst', 25),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29),
(184, 'Marks Johnson', '021, Big street, NY', 'Male', 'Head of IT', 41),
(185, 'Mak Pub', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 40),
(186, 'Louis C. Charmis', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 40);

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

Friday, 27 July 2018

How to Load CSV File in JQuery Datatables using Ajax PHP



This post covert How to Import CSV file data into JQuery Datatables plugin using PHP script with Ajax without refresh of web page. CSV file is stand for Comma-Seperated values which stores tabular data like numbers or text in plain text format which has been widely used for large amount of data. And same way jquery Datatables plugin is a powerful jquery plugin for display data on webpage in tabular format with extra feature like searching of table data, sorting of data, pagination of data with client side or server side processing without writing single line of code. So, Now in this post we have discuss how to use CSV file with JQuery Datatables plugin or How to load or Import CSV file data in Jquery Datatables plugin on web page.

In CSV file we can store very large amount of data then we want to search data in CSV file then it is very difficult to find any data from CSV file but if that data has been loaded into Datatables plugin in tabular format then we can easily search or filter data in this plugin. So there is a question how to load CSV File data into JQuery Datatables in our web application. For solve this problem we have make this post in which we have covered step by step to import CSV File string delimited data into tabular format in Jquery Datatables plugin using PHP code with Ajax and can perform client side processing of CSV file data.

For Importing of CSV file Data first we have to upload CSV file. For uploading of CSV file here we have use Ajax, so by using Ajax with PHP we will upload file without refresh of webpage. When we have send file to PHP script using Ajax then first by using fopen() function we have read csv file and store csv file data into one variable. After this by using fgetcsv() function we have converted csv file plain text data into PHP array. After this for fetch data from PHP Array we have use while loop and store into single array in Array format. Lastly for convert PHP array to JSON string we have use json_encode() function and send to Ajax request and under success function Ajax we have initialiaze Jquery Datatables plugin by using DataTable() method with json data source which has been define in data option. This way we can import or load CSV file data into Jquery Datatables plugin by using Ajax with PHP. Below you can find complete source code of this tutorial.










index.php



<?php

//index.php

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Import CSV File into 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>
  <style>
  .box
  {
   max-width:600px;
   width:100%;
   margin: 0 auto;;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Import CSV File into Jquery Datatables using PHP Ajax</h3>
   <br />
   <form id="upload_csv" method="post" enctype="multipart/form-data">
    <div class="col-md-3">
     <br />
     <label>Add More Data</label>
    </div>  
                <div class="col-md-4">  
                   <input type="file" name="csv_file" id="csv_file" accept=".csv" style="margin-top:15px;" />
                </div>  
                <div class="col-md-5">  
                    <input type="submit" name="upload" id="upload" value="Upload" style="margin-top:10px;" class="btn btn-info" />
                </div>  
                <div style="clear:both"></div>
   </form>
   <br />
   <br />
   <div class="table-responsive">
    <table class="table table-striped table-bordered" id="data-table">
     <thead>
      <tr>
       <th>Student ID</th>
       <th>Student Name</th>
       <th>Phone Number</th>
      </tr>
     </thead>
    </table>
   </div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){
 $('#upload_csv').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"import.php",
   method:"POST",
   data:new FormData(this),
   dataType:'json',
   contentType:false,
   cache:false,
   processData:false,
   success:function(jsonData)
   {
    $('#csv_file').val('');
    $('#data-table').DataTable({
     data  :  jsonData,
     columns :  [
      { data : "student_id" },
      { data : "student_name" },
      { data : "student_phone" }
     ]
    });
   }
  });
 });
});

</script>


import.php



<?php

//import.php

if(!empty($_FILES['csv_file']['name']))
{
 $file_data = fopen($_FILES['csv_file']['name'], 'r');
 fgetcsv($file_data);
 while($row = fgetcsv($file_data))
 {
  $data[] = array(
   'student_id'  => $row[0],
   'student_name'  => $row[1],
   'student_phone'  => $row[2]
  );
 }
 echo json_encode($data);
}

?>


tbl_student.csv



student_id,student_name,student_phone
1,Pauline S. Rich,412-735-0224
2,Sarah C. White,320-552-9961
3,Samuel L. Leslie,201-324-8264
4,Norma R. Manly,478-322-4715
5,Kimberly R. Castro,479-966-6788
6,Elaine R. Davis,701-685-8912
7,Concepcion S. Gardner,607-829-8758
8,Patricia J. White,803-789-0429
9,Michael M. Bothwell,214-585-0737
10,Ronald C. Vansickle,630-571-4107
11,Clarence A. Rich,904-459-3747
12,Elizabeth W. Peterson,404-380-9481
13,Renee R. Hewitt,323-350-4973
14,John K. Love,337-229-1983
15,Teresa J. Rincon,216-394-6894
16,Erin S. Huckaby,503-284-8652
17,Brian A. Handley,989-304-7122
18,Michelle A. Polk,540-232-0351
19,Wanda M. Brown,718-262-7466
20,Phillip A. Hatcher,407-492-5727
21,Dennis J. Terrell,903-863-5810
22,Britney F. Johnson,972-421-6933
23,Rachelle J. Martin,920-397-4224
24,Leila E. Ledoux,615-425-9930
25,Darrell A. Fields,708-887-1913
26,Linda D. Carter,909-386-7998
27,Melva J. Palmisano,630-643-8763
28,Jessica V. Windham,513-807-9224
29,Karen T. Martin,847-385-1621
30,Jack K. McDonough,561-641-4509
31,John M. Williams,508-269-9346
32,Amelia W. Davis,347-537-8052
33,Gertrude W. Lawrence,510-702-7415
34,Michael L. Harris,252-219-4076
35,Casey A. Groves,810-334-9674
36,James H. Wilson,865-259-6772
37,James A. Wesley,443-217-1859
38,Armando C. Gay,716-252-9230
39,James M. Duarte,402-840-0541
40,Jason E. West,360-610-7730
41,Gloria H. Saucedo,205-861-3306
42,Paul T. Moody,914-683-4994
43,Sandra L. Williams,310-335-1336
44,Elaine T. Deville,626-513-8306
45,Robyn L. Spangler,754-224-7023
46,Sam A. Pino,806-823-5344
47,Joseph H. Marble,201-917-2804
48,Mark M. Bassett,206-592-4665
49,Edgar M. Billy,978-365-0324
50,Connie M. Yang,815-288-5435

Thursday, 26 July 2018

5 Things About Codeigniter That You Might Regret Not Knowing

5 Things About Codeigniter That You Might Regret Not Knowing


Developed by the British Columbia Institute of Technology, the CodeIgniter is an open-source software. In an open-source software, the people who have the copyright grants the users various rights. They can be rights to study, to change and also to distribute to someone for some purpose. The CodeIgniter developers is used for the purpose of designing dynamic websites with PHP.

With this brief introduction, we will directly now get to the point. While many of the people out there are very well acquainted with the working of the software, there are many features which are yet to be discovered by a majority of the people. For them, this is the article, to know all the features of the software and gain maximum benefit from it.

  • Setting up the database connection: Even many of the expert users do not know how to do this part. But as the saying goes, a little learning goes a long way, here is your chance to learn it. All you need to do for setting up the connection is first to open the database.php. This will be located in the config folder. If it is not there, you might refer to the documentation. Sometimes, you might also face errors which will show that the connection is not possible with the current setting. Then also you will need to change the settings from this file.
  • Switching to URI routing: Often, the URL name with which we are working is just too big to work with, isn’t it? Well, here is your chance to change it. The given URI generally follow this pattern, example.com/class/function/id/. There is always a one-to-one relation between a URL and the controller class/method corresponding to it. You can also remap the relation if you wish. Remapping is done to enable you to have different class/methods than the one which is corresponding to the URL.
  • Using the feature for autoloading: Using the autoload function will enable you to load libraries, helper or models automatically. For this purpose, you will need to open the autoload.php. The file will be located in the config folder like that of the download.php one. The models, helpers and libraries that you will load will be initialized for each time that you run the system. After opening the autoload.php, all you need to do is to add the item that you want to load in the autoload array. You will find the specific instructions in the file corresponding to what you wish to load.
  • MVC architecture support by the software: The software CodeIgniter has very few requirements for the server. It runs on a model, view, controller abbreviated as MVC architecture. This feature, though not new, supports the basic coding framework of a lot of software as this architecture is comparatively easy to configure. Even this can be used for the purpose of designing big apps and to manage them properly.
  • Support for the software: Though not very often, but during a long course of use, you might face some errors in the CodeIgniter software. This may disrupt your work that is completely based on the software and you may seem at a loss. But what you probably do not is of this most useful software is that it has a very efficient error support. To help you out in such difficult situations, the CodeIgniter forum has a large number of members and moreover, you will have access to the wiki too.

You probably might be thinking that the features are not so simple and we make it sound here. Take our word for it, it is even more user-friendly and easy that we tell you it is. And in case you are facing any error or cannot access any function, the CodeIgniter family is always at your service.




About the Author

Nancy Patterson is a Marketing Manager a Hire Php Developer. She is a resident of United Kingdom.nancy is also an experienced Php developer. She also likes to share her thoughts,cms development, hire codeigniter developer, and web development techniques.