Thursday, 16 August 2018

Live Table Add Edit Delete using PHP with jsGrid Plugin



Live Inline CRUD operation of Create, Read, Update and Delete within a area of grid view. Live inline CRUD will add feature like adding new data and make changes in existing data dynamically using jquery with Ajax. Now here is one question how can we perform this all things, for this here we have use jsGrid jquery plugin which is lightweight jQuery grid plugin in which we can perform all CRUD operation like insert update delete and Read data using Ajax with PHP and Mysql database.

In our some previous tutorial we have discuss this things but in that we have do every things manually and we have converted table data field into editable by using contenteditable attribute and in that tutorial we have only use textbox field only but here by using jsGrid plugin we can also use most of all html input field.

jsGrid is a very popular lightweight jquery grid plugin and it is especially design for add edit delete inline mysql table data using Ajax and it is compatible with all programming language because it has use json data for sending and receiving. So, here we have use this plugin with PHP script and make simple inline insert update delete mysql data using Ajax. This tutorial will help us to add, edit and delete records into grid using PHP and Mysql. This plugin has use Ajax request for add, edit and delete data using PHP with mysql. jsGrid is a simple and very lightweight client side data grid plugin based on jQuery and by using this plugin we can perform all operation like insert new records, filter existing records, edit existing records, delete records, pagination of data and sorting of data. By using this plugin in short code you can perform very big task.

In below step by step source code you can find how can we integrate jsGrid plugin with PHP system and How can we fetch data from Mysql database and load into jsGrid plugin. How can we add or insert new records into Mysql by using jsGrid plugin with PHP. How can we edit existing mysql data by using jsGrid with PHP. How can we delete single mysql records in jsGrid using PHP. And lastly how can we make single page inline table add edit delete PHP application using this jsGrid plugin.











Source Code



--
-- Database: `testing`
--

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

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

CREATE TABLE `sample_data` (
  `id` int(10) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `age` int(3) NOT NULL,
  `gender` enum('male','female') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `sample_data`
--

INSERT INTO `sample_data` (`id`, `first_name`, `last_name`, `age`, `gender`) VALUES
(3, 'Tiny', 'Marry', 19, 'female'),
(4, 'Dolores', 'Brooks', 29, 'female'),
(5, 'Cindy', 'Dahl', 24, 'female'),
(6, 'George', 'Fagan', 30, 'male'),
(7, 'Chelsea', 'Mendoza', 18, 'female'),
(8, 'Wayne', 'Hodges', 27, 'male'),
(9, 'Keith', 'Watkin', 26, 'male'),
(10, 'Eric', 'Smith', 31, 'male'),
(11, 'Robert', 'Owens', 42, 'male'),
(12, 'Candace', 'Hand', 27, 'female'),
(13, 'Hortencia', 'Bell', 30, 'female'),
(14, 'William', 'Sosa', 36, 'male'),
(15, 'Patricia', 'Davis', 23, 'female'),
(17, 'Nancy', 'Sedlacek', 21, 'female');

--
-- 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, AUTO_INCREMENT=18;


index.php



<html>  
    <head>  
        <title>Inline Table Insert Update Delete in PHP using jsGrid</title>  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
  <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
  <style>
  .hide
  {
     display:none;
  }
  </style>
    </head>  
    <body>  
        <div class="container">  
   <br />
   <div class="table-responsive">  
    <h3 align="center">Inline Table Insert Update Delete in PHP using jsGrid</h3><br />
    <div id="grid_table"></div>
   </div>  
  </div>
    </body>  
</html>  
<script>
 
    $('#grid_table').jsGrid({

     width: "100%",
     height: "600px",

     filtering: true,
     inserting:true,
     editing: true,
     sorting: true,
     paging: true,
     autoload: true,
     pageSize: 10,
     pageButtonCount: 5,
     deleteConfirm: "Do you really want to delete data?",

     controller: {
      loadData: function(filter){
       return $.ajax({
        type: "GET",
        url: "fetch_data.php",
        data: filter
       });
      },
      insertItem: function(item){
       return $.ajax({
        type: "POST",
        url: "fetch_data.php",
        data:item
       });
      },
      updateItem: function(item){
       return $.ajax({
        type: "PUT",
        url: "fetch_data.php",
        data: item
       });
      },
      deleteItem: function(item){
       return $.ajax({
        type: "DELETE",
        url: "fetch_data.php",
        data: item
       });
      },
     },

     fields: [
      {
       name: "id",
    type: "hidden",
    css: 'hide'
      },
      {
       name: "first_name", 
    type: "text", 
    width: 150, 
    validate: "required"
      },
      {
       name: "last_name", 
    type: "text", 
    width: 150, 
    validate: "required"
      },
      {
       name: "age", 
    type: "text", 
    width: 50, 
    validate: function(value)
    {
     if(value > 0)
     {
      return true;
     }
    }
      },
      {
       name: "gender", 
    type: "select", 
    items: [
     { Name: "", Id: '' },
     { Name: "Male", Id: 'male' },
     { Name: "Female", Id: 'female' }
    ], 
    valueField: "Id", 
    textField: "Name", 
    validate: "required"
      },
      {
       type: "control"
      }
     ]

    });

</script>



<?php

//fetch_data.php

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

$method = $_SERVER['REQUEST_METHOD'];

if($method == 'GET')
{
 $data = array(
  ':first_name'   => "%" . $_GET['first_name'] . "%",
  ':last_name'   => "%" . $_GET['last_name'] . "%",
  ':age'     => "%" . $_GET['age'] . "%",
  ':gender'    => "%" . $_GET['gender'] . "%"
 );
 $query = "SELECT * FROM sample_data WHERE first_name LIKE :first_name AND last_name LIKE :last_name AND age LIKE :age AND gender LIKE :gender ORDER BY id DESC";

 $statement = $connect->prepare($query);
 $statement->execute($data);
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'id'    => $row['id'],   
   'first_name'  => $row['first_name'],
   'last_name'   => $row['last_name'],
   'age'    => $row['age'],
   'gender'   => $row['gender']
  );
 }
 header("Content-Type: application/json");
 echo json_encode($output);
}

if($method == "POST")
{
 $data = array(
  ':first_name'  => $_POST['first_name'],
  ':last_name'  => $_POST["last_name"],
  ':age'    => $_POST["age"],
  ':gender'   => $_POST["gender"]
 );

 $query = "INSERT INTO sample_data (first_name, last_name, age, gender) VALUES (:first_name, :last_name, :age, :gender)";
 $statement = $connect->prepare($query);
 $statement->execute($data);
}

if($method == 'PUT')
{
 parse_str(file_get_contents("php://input"), $_PUT);
 $data = array(
  ':id'   => $_PUT['id'],
  ':first_name' => $_PUT['first_name'],
  ':last_name' => $_PUT['last_name'],
  ':age'   => $_PUT['age'],
  ':gender'  => $_PUT['gender']
 );
 $query = "
 UPDATE sample_data 
 SET first_name = :first_name, 
 last_name = :last_name, 
 age = :age, 
 gender = :gender 
 WHERE id = :id
 ";
 $statement = $connect->prepare($query);
 $statement->execute($data);
}

if($method == "DELETE")
{
 parse_str(file_get_contents("php://input"), $_DELETE);
 $query = "DELETE FROM sample_data WHERE id = '".$_DELETE["id"]."'";
 $statement = $connect->prepare($query);
 $statement->execute();
}

?>

iPhone Touch Disease: What It Is and What to Do About It

iPhone Touch Disease: What It Is and What to Do About It


Is your iPhone acting creepy? Is it stuck or simply freezes on the Apple logo screen? Is it not responding to your touch? If so, it typically means that your iPhone has a touch disease. I am sure it would be a frustrating thing for you but don’t fret, you can fix it! Here I have come up with some of the best things you can do with your sick or even broken iPhone.

The popularity of Apple iPhones is clear from the fact that there are various models have come into the market and millions of people all over the world use them to the best of their choices. However, at the same time problems related to these iPhone devices are also numerous. One of the most common problems iPhone users usually encounter is that the iPhone gets stuck and becomes unresponsive to touch; it is called an iPhone touch disease.

What Are iPhone Models Affected With Touch Disease?


Any iPhone model might be affected but the iPhone 6 series are reported as the most affected Apple devices; iPhone 6 Plus had the most complaints about the touch disease.

So, if you are one of those whose iPhones are suffering from the touch disease then the best solution is to replace the touchscreen you can opt for. However, if you have cracked or broken your iPhone’s screen, it’s better to Sell broken iPhone. The repair/replacement cost of a broken iPhone is too high because this kind of breakage is not covered under Apple’s Warranty. On the other hand, by selling a broken iPhone, you can make the most money that you can use for buying a new one.

How Will You Identify Your iPhone Is Suffering From a Touch Disease?


If you own an iPhone 6, 6 Plus, 6s, or 6s Plus, the chances are that you may experience your iPhone’s touch disease. Here are two common symptoms of the touch disease you can encounter:

  • Your iPhone’s touchscreen is not responding on your taps properly. This simply means that your iPhone’s screen freezes and taps on the screen are not being recognised or pressing the home button does not do anything, as well as pinching or zooming are also not operating.
  • Your iPhone’s screen gets a flickering gray bar at the top.

What Are The Causes Of iPhone Touch Disease?


It is the most debatable point; you must know the cause of the disease so that you can cure it properly. When it comes to iPhone touch disease, Apple says that the disease is triggered by repeatedly dropping the iPhone on hard surfaces or simply when you misbehave with your iPhone, it might catch the touch disease.

Conversely, some experts say it is a design flaw in the iPhone because it can happen on iPhone devices that have not been dropped; it might be due to some manufacturing flaws lie when the connection of touchscreen controller chips inside the screen is damaged.

How to Fix the Touch Disease on An iPhone?


If you want to fix the touch disease on an iPhone, Apple offers a Repair program that costs US$149. If your iPhone is covered by manufacturer’s warranty then you can visit a nearby AppleCare+ store and get your iPhone’s screen replaced to bring it back to its normal condition.

I agree it’s not a cheap solution. So, if you are not ready to spend this huge amount on the iPhone repair then it is advised you should sell it and buy a new one. Selling an old or broken phone helps you get some money that you can devote to purchasing a new iPhone of your choice.

Mobile Phone Recycling- The Best Way of Selling Old or Broken Phones


Most of the people put their old or broken mobile phones in the handy drawers or cupboards somewhere in their homes and then after sometimes they simply discard them in trash cans because these devices become useless. Unfortunately, when electronic devices are ended up in the landfills, there is an increase in e-waste and it leads to air and water pollution. Mobile phones contain numerous toxic substances such as lead, cadmium, beryllium, coltan, mercury, arsenic, selenium, and flame retardants that can contaminate the environment.

So, mobilephone recycling is the best way to get rid of old and damaged phones. Mobile recycling companies not only take your old, unwanted mobile phones for recycling but also pay you some cash for them. Since there are numerous phone recycling companies out there online, a lot of questions might come in your mind such as: with so many recycling sites online you can use, which one is the best? Which one is right for you? How do you get the most cash in exchange for your old or broken Phone? That's where comparing comes in. By making a comparison of top recycling firms through a comparison site, you can search for your mobile phone and get the best prices for it in one place offered by all the top recyclers. This will save you time and hassle that you may experience in browsing the recycling sites individually one by one to get the top price for Selling your Phone that you no longer want to use.

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;