Saturday, 23 June 2018

How to use Google Chart API in Laravel

Now a days Google has provide us different type of popular API like Google map, Google chart, Google Analytics etc. From all this API Google charts API is widely used for creating or build different type of chart and this is very simple to integrate with our existing web application. So, in this post we are going to create pie chart by using Google Chart API in Laravel application.

This Google charts API provide us different type of charts like Area chart, Bar chart, Line Chart, Column chart, Geo chart etc. In this blog we will use Pie chart of Google Chart library and display data in stylish graphical format. For How to use Google chart library in your laravel application, you have to just follow following step.



Step 1 : Database


For build Pie chart for that we want to required some data in our database. So here we have one tbl_employee table. In this table we have insert some employee data. From this data we want to display how many percentage of male and female employee working.


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






Step 2: Set Route


This is second steps and in this steps we have to set route for create view in browser. For this we have to open routes/webs.php file and write following route code in it.


<?php

Route::get('/laravel_google_chart', 'LaravelGoogleGraph@index');

?>


Step 3: Make Controller


In this step first we have create Controller in our Laravel application. For this we have to go to command prompt and write following command.


php artisan make:controller LaravelGoogleGraph


Above command will make controller in app/Http/Controllers/LaravelGoogleGraphp.php We have to open this controller and create index() method in it for fetch data from mysql table and convert into json string and lastly it will send that data to view file. For this process you can find source code below.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LaravelGoogleGraph extends Controller
{
    function index()
    {
     $data = DB::table('tbl_employee')
       ->select(
        DB::raw('gender as gender'),
        DB::raw('count(*) as number'))
       ->groupBy('gender')
       ->get();
     $array[] = ['Gender', 'Number'];
     foreach($data as $key => $value)
     {
      $array[++$key] = [$value->gender, $value->number];
     }
     return view('google_pie_chart')->with('gender', json_encode($array));
    }
}


Step 4: Make View File


This last step for how to use Google Chart API in Laravel and in this step we have to make view file google_pie_chart.blade.php in resources/views folder. This is our output which will display chart on web page in browser. In this file we have write javascript code for generate pie chart by using Google Chart API and data has been get from Laravel controller.


<!DOCTYPE html>
<html>
 <head>
  <title>Make Google Pie Chart in Laravel</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <style type="text/css">
   .box{
    width:800px;
    margin:0 auto;
   }
  </style>
  <script type="text/javascript">
   var analytics = <?php echo $gender; ?>

   google.charts.load('current', {'packages':['corechart']});

   google.charts.setOnLoadCallback(drawChart);

   function drawChart()
   {
    var data = google.visualization.arrayToDataTable(analytics);
    var options = {
     title : 'Percentage of Male and Female Employee'
    };
    var chart = new google.visualization.PieChart(document.getElementById('pie_chart'));
    chart.draw(data, options);
   }
  </script>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Make Google Pie Chart in Laravel</h3><br />
   
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Percentage of Male and Female Employee</h3>
    </div>
    <div class="panel-body" align="center">
     <div id="pie_chart" style="width:750px; height:450px;">

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


So, this is complete step by step process for How to integrate Google Charts API in Laravel Application and build pie charts in Laravel application by using Google Charts Library.

Thursday, 21 June 2018

PHP Mysql Pagination using AngularJS



If you are looking for AngularJS tutorial on paginatin then in this post we have describe how to make pagination by using AngularJS with PHP. If we have working on any dynamic website by using PHP then for display mysql table data on web page in tabular format then we would required pagination. Because by using Pagination, it will divided large amount of data into different part and it will load only some number of rows on web page and suppose we want to see next data then we have to click on next link button, so when we have click on link then it has send request for fetch next data and display on web page in tabular format without refresh of web page. So by using Pagination we have reduce server load, because if we have not use pagination then it will fetch all data from database at the same time and it will reduce our website speed also. But by using pagination it will load only some rows of data and it will load next data as pere requirement.

Pagination is a required feature in web development and this feature we want to make by using AngularJS with PHP. For make pagination by using AngularJS with PHP, for this we have use "dirPagination" AngularJS module, this module is for create pagination with AngularJS. By using this module we can easily pagination by using AngularJS with any dynamic language and it has reduce our server side code and it has directly make pagination link. For make pagination by using this AngularJS module we have to just send data in JSON string format then it will automatically convert this data into pagination with pagination link. We have to just define how many data we have display per page in "itemsPerPage" option of "dir-paginate" directoyr. This is directory work as same like ng-repeat directory. By using this directory we can print data on web page but this directory has been make by this AngularJS module.

So, if you are using AngularJS as front-end and PHP as backend and we want to make pagination in your web application then this tutorial will helpful. Because in this post we have describe PHP pagination using AngularJS. Below you can find source code of Pagination using AngularJS with PHP.










Source Code


index.php



<?php
//index.php

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysql Pagination using AngularJS</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
        <script src="dirPaginate.js"></script>
 </head>
 <body>
  <div class="container" ng-app="paginationApp" ng-controller="paginationController">
   <br />
   <h3 align="center">PHP Mysql Pagination using AngularJS</h3>
   <br />
   <div class="table-responsive">
    <table class="table table-striped table-bordered">
     <thead>
      <tr>
       <th>Student Name</th>
       <th>Student Phone</th>
      </tr>
     </thead>
     <tbody>
      <tr dir-paginate="singleData in allData|itemsPerPage:10">
       <td>{{ singleData.student_name }}</td>
       <td>{{ singleData.student_phone }}</td>
      </tr>
     </tbody>
    </table>
   </div>
   <div align="right">
    <dir-pagination-controls max-size="5" direction-links="true" boundary-links="true" >
    </dir-pagination-controls>
   </div>
  </div>
 </body>
</html>

<script>
var pagination_app = angular.module('paginationApp', ['angularUtils.directives.dirPagination']);
pagination_app.controller('paginationController', function($scope, $http){
 $http.get('fetch.php').success(function(data){
  $scope.allData = data;
 });
});
</script>


fetch.php



<?php

//fetch.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$query = "SELECT * FROM tbl_student ORDER BY student_id DESC";
$statement = $connect->prepare($query);
if($statement->execute())
{
 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }
 echo json_encode($data);
}

?>





Tuesday, 19 June 2018

How to Create Unique URL Slug in PHP



Creating of Slug from title in PHP is very easy and we can easily do this things. But How can we generate unique url slug from same title in PHP. So, this things we have dicuss here. When we have developed any dynamic ecommerce or content based or any website which general public can access which has been developed PHP then generating or creating of slug is very important task, because we want to generate every url must be unique if it is duplicate then it will load different result on web page.

So, when we have store dynamic website content into Mysql database then at that time it will typical pattern for fetching data and generate unique slug which has been based on particular title. This unique and seo friendly slug will gives not only to users but also search engine can human friendly way to get access website dynamic page from this unique slug. So, Generating or Creating of unique slug is very important task for any PHP web developers.

If we have use any PHP framework for developing website then we can get easily make slug from title and but here we have discuss how to make url slug using PHP and it must be unique. So, in this post we have describe step by step how can we generate unique slug by using PHP. Here we have store slug data in mysql table and when we have generate new slug from particular title then it will check in database particular slug or url already present in our database or not, it is present then it will count how many time it has been appear in database and lastly it will append maximum number plus one number append into slug and make in unique. Below you can find complete source code for how to create unique slug in php.








Source Code



<?php
//header.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$slug = '';
if(isset($_POST["create"]))
{
 //$slug = preg_replace(pattern, replacement, subject)
 $slug = preg_replace('/[^a-z0-9]+/i', '-', trim(strtolower($_POST["title"])));

 $query = "SELECT slug_url FROM slug WHERE slug_url LIKE '$slug%'";
 
 $statement = $connect->prepare($query); 
 if($statement->execute())
 {
  $total_row = $statement->rowCount();
  if($total_row > 0)
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    $data[] = $row['slug_url'];
   }
   
   if(in_array($slug, $data))
   {
    $count = 0;
    while( in_array( ($slug . '-' . ++$count ), $data) );
    $slug = $slug . '-' . $count;
   }
  }
 }

 $insert_data = array(
  ':slug_title'  => $_POST['title'],
  ':slug_url'   => $slug
 );
 $query = "INSERT INTO slug (slug_title, slug_url) VALUES (:slug_title, :slug_url)";
 $statement = $connect->prepare($query);
 $statement->execute($insert_data);

 //echo $slug;
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>How Create Unique Slug in PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <style>
  .box
  {
   max-width:600px;
   width:100%;
   margin: 0 auto;;
  }
  </style>
 </head>
 <body>
  <div class="container box">
   <br />
   <h3 align="center">How Create Unique Slug in PHP</h3>
   <br />
   <form method="post">
    <div class="form-group">
     <label>Enter Title for Slug</label>
     <input type="text" name="title" class="form-control" required />
    </div>
    <br />
    <div class="form-group">
     <input type="submit" name="create" class="btn btn-info" value="Create" />
    </div>
    <br />
    <h4>Generated Slug - <?php echo $slug; ?></h4>
   </form>
  </div>
 </body>
</html>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `slug`
--

CREATE TABLE `slug` (
  `slug_id` int(11) NOT NULL,
  `slug_title` varchar(255) NOT NULL,
  `slug_url` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `slug`
--
ALTER TABLE `slug`
  ADD PRIMARY KEY (`slug_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `slug`
--
ALTER TABLE `slug`
  MODIFY `slug_id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;

Friday, 15 June 2018

Laravel - How to Generate Dynamic PDF from HTML using DomPDF



Making of Dynamic PDF is required feature of any commercial web application, so here we have publish this post in which we have describe how to create dynamic pdf file in Laravel by using DomPDF library. Suppose we have working on any enterprise level web application by using Laravel then at that time we want to required to make output of our application in PDF report format from dynamic Mysql database. From this post we have make simple tutorial in which we have describe how to can we generate dynamic PDF file in step by step process which better understading to beginner laravel programmer.

In this tutorial we have use laravel-dompdf package for generate dynamic pdf file and by using this package we can also download pdf file in our local computer also. Here we have use mysql customer table, in which we have already inserted some data for create dynamic pdf file from that data in tabular format. For display data in proper in table in pdf file we have also add some inline css in html table code, because we have make pdf file from html by using dompdf package in Laravel.







Step 1 - Download Laravel Dompdf Package


For create PDF file in Laravel first we want to download laravel-dompdf package. For this first we want to write following command in command prompt terminal.


composer require barryvdh/laravel-dompdf


Download this packege we have to register this package into Laravel working environment, for this we have to open config/app.php file and add service provider and aliase details.


'providers' => [
        ..........
        Barryvdh\DomPDF\ServiceProvider::class,
    ],

    'aliases' => [
        ..........
        'PDF' => Barryvdh\DomPDF\Facade::class,
    ],


Step 2 - Create Controller


After this we have to create controller in our Laravel application by using composer command. This controller will handle http requrest to convert html code to PDF file.


php artisan make:controller DynamicPDFController


This command will make controller in app/Http/Controllers folder with name like DynamicPDFController.php. In this controller first we have to make index() method for fetch data from database and here for fetch data we have to get_customer_data() method and after this in index() method we have send data to view file. For convert HTML data to PDF we have make another method pdf() by using this method it will convert html code to PDF file. For html data here we have use convert_customer_data_to_html() method. Below you can find complete controller source code below.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use PDF;

class DynamicPDFController extends Controller
{
    function index()
    {
     $customer_data = $this->get_customer_data();
     return view('dynamic_pdf')->with('customer_data', $customer_data);
    }

    function get_customer_data()
    {
     $customer_data = DB::table('tbl_customer')
         ->limit(10)
         ->get();
     return $customer_data;
    }

    function pdf()
    {
     $pdf = \App::make('dompdf.wrapper');
     $pdf->loadHTML($this->convert_customer_data_to_html());
     return $pdf->stream();
    }

    function convert_customer_data_to_html()
    {
     $customer_data = $this->get_customer_data();
     $output = '
     <h3 align="center">Customer Data</h3>
     <table width="100%" style="border-collapse: collapse; border: 0px;">
      <tr>
    <th style="border: 1px solid; padding:12px;" width="20%">Name</th>
    <th style="border: 1px solid; padding:12px;" width="30%">Address</th>
    <th style="border: 1px solid; padding:12px;" width="15%">City</th>
    <th style="border: 1px solid; padding:12px;" width="15%">Postal Code</th>
    <th style="border: 1px solid; padding:12px;" width="20%">Country</th>
   </tr>
     ';  
     foreach($customer_data as $customer)
     {
      $output .= '
      <tr>
       <td style="border: 1px solid; padding:12px;">'.$customer->CustomerName.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->Address.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->City.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->PostalCode.'</td>
       <td style="border: 1px solid; padding:12px;">'.$customer->Country.'</td>
      </tr>
      ';
     }
     $output .= '</table>';
     return $output;
    }
}


Step 3 - Create view file


After this we have make view file in resources/view/dynamic_pdf.blade.php. This file has received data from controller index() method and display dynamic data in html table format. After this we have make on button for convert this html data to pdf file. When we have click on this button then it has send request to pdf() method of controller which will convert html to PDF file by using dompdf package in laravel which we can see on web page.


<!DOCTYPE html>
<html>
 <head>
  <title>Laravel - How to Generate Dynamic PDF from HTML using DomPDF</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
   }
  </style>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Laravel - How to Generate Dynamic PDF from HTML using DomPDF</h3><br />
   
   <div class="row">
    <div class="col-md-7" align="right">
     <h4>Customer Data</h4>
    </div>
    <div class="col-md-5" align="right">
     <a href="{{ url('dynamic_pdf/pdf') }}" class="btn btn-danger">Convert into PDF</a>
    </div>
   </div>
   <br />
   <div class="table-responsive">
    <table class="table table-striped table-bordered">
     <thead>
      <tr>
       <th>Name</th>
       <th>Address</th>
       <th>City</th>
       <th>Postal Code</th>
       <th>Country</th>
      </tr>
     </thead>
     <tbody>
     @foreach($customer_data as $customer)
      <tr>
       <td>{{ $customer->CustomerName }}</td>
       <td>{{ $customer->Address }}</td>
       <td>{{ $customer->City }}</td>
       <td>{{ $customer->PostalCode }}</td>
       <td>{{ $customer->Country }}</td>
      </tr>
     @endforeach
     </tbody>
    </table>
   </div>
  </div>
 </body>
</html>


Step 4 - Add Route


This is last step for generate dynamic pdf file in laravel by using dompdf package and here we want to set route for index() and pdf() method of DynamicPDFController.php file. For this we have to go to app/Http/routes.php and write following code for set route in our laravel application.


Route::get('/dynamic_pdf', 'DynamicPDFController@index');

Route::get('/dynamic_pdf/pdf', 'DynamicPDFController@pdf');


So, this is complete step by step process for create PDF file in Laravel by using Dompdf package.

Monday, 11 June 2018

Auto Refresh Div Content using AngularJS in PHP


In this post we will learn How can we auto refresh any Div tag dynamic content or data by using AngularJS with PHP Script. Because refreshing content of any particular html element of web application page is one of the required functionality in Dynamic web development. For this JavaScript has provide us to use setInterval() method for execute the same task on regular interval with specified time. But we want to do this things in AngularJS, so AngularJS has the wrapper of setInterval() in $Interval angular service module. By using this angular service module we can repeat the same task on regular interval of time.

So, here for refresh a DIV or any element content or data in specified time, we have use $interval service. This Angular service has done same task which we have done by using setInterval() method of javascript but $interval has give us more control like promis callback which can be cancel or stop execute of refresh of data.

For learn how can we use $interval service for Auto refresh of Div content without refresh of web page. So, here we have use PHP script and make simple Chat application by using AngularJS with PHP. In this chat application we have load chat data in Div tag by using AngularJS function which call PHP script for fetch data from Mysql data and display under Div tag. Now we want to auto refresh this Div chat data on every 5 seconds, for this here we have use $interval service of Angular. This service we can use same as setInterval(), in this service also we have put our fetchData() function and set time interval of 5 seconds, so on every 5 second $interval service has called fetchData() function which send request to PHP script for fetch data from Mysql chat table and then after it will display under Div without refresh of webpage. If want to make robust web application by using AngularJS with PHP then this source code will helpful. So, this way it will auto refresh div content by using AngularJS $interval service with PHP.









Source Code



--
-- Database: `testing`
--

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

--
-- Table structure for table `chat`
--

CREATE TABLE `chat` (
  `chat_id` int(11) NOT NULL,
  `chat_content` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `chat`
--
ALTER TABLE `chat`
  ADD PRIMARY KEY (`chat_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `chat`
--
ALTER TABLE `chat`
  MODIFY `chat_id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;


database_connection.php



<?php

//database_connection.php

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



?>


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Auto Refresh Div Content using AngularJS in PHP</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  #load_tweets
    {
      padding:16px;
      background-color:#f1f1f1;
      margin-bottom:30px;
    }
    #load_tweets li
    {
      padding:12px;
      border-bottom:1px dotted #ccc;
      list-style: none;
    }
  </style>
 </head>
 <body>
  <br />
   <h3 align="center">Auto Refresh Div Content using AngularJS in PHP</h3>
  <br />
  <div ng-app="autoRefreshApp" ng-controller="autoRefreshController" class="container" style="width:100%; max-width:600px;">
   <h3 align="center">Chat Page</h3>

   <div class="alert alert-success alert-dismissible" ng-show="success">
    <a href="#" class="close" aria-label="close">&times;</a>
    {{ successMessage }}
   </div>

   <form method="post" ng-model="form_data" ng-submit="submitForm()">
    <div class="form-group">
     <label>Enter Your Message</label>
     <textarea name="content" class="form-control" ng-model="form_data.content"></textarea>
    </div>
    <div class="form-group" align="right">
     <input type="submit" name="submit" class="btn btn-info" value="Send" />
    </div>
   </form>
   <div id="load_tweets">
    <ul>
     <li ng-repeat="messageData in messagesData">
      {{ messageData.chat_content }}
     </li>
    </ul>
   </div>
  </div>
 </body>
</html>

<script>

var app = angular.module('autoRefreshApp', []);

app.controller('autoRefreshController', function($scope, $http, $interval){

 $scope.success = false;

 $scope.submitForm = function(){
  $http({
   method:"POST",
   url:'insert.php', 
   data:$scope.form_data
  }).success(function(data){
   if(data.message != '')
   {
    $scope.form_data = null;
    $scope.success = true;
    $scope.successMessage = data.message;
    $interval(function(){
     $scope.success = false;
    }, 5000);
   }
  });
 };

 $scope.fetchData = function(){
  $http.get('fetch_data.php').success(function(data){
   $scope.messagesData = data;
  });
 };

 $interval(function(){
  $scope.fetchData();
 }, 5000);

});



</script>


insert.php



<?php

//insert.php

include("database_connection.php");

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

if(!empty($form_data->content))
{
 $data = array(
  ':chat_content'  => $form_data->content
 );
 $query = "
 INSERT INTO chat 
 (chat_content) VALUES (:chat_content)
 ";
 $statement = $connect->prepare($query);
 if($statement->execute($data))
 {
  $output = array(
   'message' => 'Message Sended'
  );
  echo json_encode($output);
 }
}

?>


fetch_data.php



<?php

//fetch_data.php

include("database_connection.php");

$query = "SELECT * FROM chat ORDER BY chat_id DESC";

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

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

?>

Saturday, 9 June 2018

How to Take Website Screen Shot From URL in PHP



Capturing of Screenshot of Web page is a one type of functionality which can be used for different purposed in our web application. If you want to put this feature in your web application then there are number of third party APIs are available on the web for capture screenshot of the website from URL. But if you want to make your own script which can take a screenshot of website from URL, then you can get this feature by using PHP with Google PageSpeed Insights API.

Mainly, This Google PageSpeed Insights API is used for calculate the speed of a web page, but we can also use this Google PageSpeed Insights API for capture a website screenshot from URL. In this post we will seen you how can we take a screen shot from URL of website by using Google PageSpeed Insights API with PHP script.

Take Screenshot of Website from URL


To take screenshot of Web page, Google PageSpeed Insights API required to pass following parameters.

  • url - In this parameters we have to pass URL of the website.
  • screenshot - This parameters screenshot=true is used for fetch screenshot data.

Below script you can see how to make a form for take website screenshot from URL which has be entered by use and after this it will load webpage screenshot on page.









Source Code - index.php



<?php

//index.php

$screen_shot_image = '';

if(isset($_POST["screen_shot"]))
{
 $url = $_POST["url"];
 $screen_shot_json_data = file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$url&screenshot=true");
 $screen_shot_result = json_decode($screen_shot_json_data, true);
 $screen_shot = $screen_shot_result['screenshot']['data'];
 $screen_shot = str_replace(array('_','-'), array('/', '+'), $screen_shot);
 $screen_shot_image = "<img src=\"data:image/jpeg;base64,".$screen_shot."\" class='img-responsive img-thumbnail'/>";
}

?>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>How to capture website screen shot from url in php</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  <style>
  .box
  {
   width:100%;
   max-width:720px;
   margin:0 auto;
  }
  </style>
 </head>
 <body>
  <div class="container box">
   <br />
   <h2 align="center">How to capture website screen shot from url in php</h2><br />
   <form method="post">
    <div class="form-group">
     <label>Enter URL</label>
     <input type="url" name="url" class="form-control input-lg" required autocomplete="off" />
    </div>
    <br />
    <br />
    <input type="submit" name="screen_shot" value="Take a Screenshot" class="btn btn-info btn-lg" />
   </form>
   <br />
   <?php
   
   echo $screen_shot_image;
   
   ?>
  </div>
  <div style="clear:both"></div>
  <br />
  
  <br />
  <br />
  <br />
 </body>
</html>

Friday, 8 June 2018

9 Questions to Ask Before Buying a Used or Reconditioned Phone


There are numerous assortments of mobile phones available in the market with different attributes to meet the needs of every mobile user. Most of us may be intent to buy a smartphone that has been released recently. However, for most of us, these expensively priced cell phones are beyond the limit that our pocket can permit. There is no need to get upset and choose some standard phones. There is a way to get a hold of a smart one at a reasonable price. You can buy a reconditioned or used mobile phone that will hardly cost you the one third or half price of its brand new counterpart.

Though getting a used or refurbished mobile phone can save you a lot, you should keep in mind that it can be a daunting task to find out a good deal- good-conditioned phone at an affordable price. Well, you can make it easier if you follow a proper guideline. Here is what you need to know about buying a reconditioned or used smartphone- and a few key questions to ask before you make a purchase.

1. Is It Really Good Idea to Buy a Used or Refurbished Phone?


Of course, it is. Most of the people think that used or reconditioned phones are poor-quality and defective ones. Well, it is not correct. It is a common practice that so many people buy sophisticated smartphones and when they are bored with them, they upgrade them with the latest ones. They return their old phones to the company during the warranty period. And then, they are resold as “Used or Reconditioned Phones” at lower prices. Though these mobile phones are old ones, they don’t have any issues with their functionality.

So, buying such kind of smartphones can be a really good deal since you can grab a good mobile phone of your choice without disturbing your monthly budget.

2. Where Can I Purchase a Second Hand or Refurbished Phone?


Nowadays, there are so many online places where you can buy second hand or refurbished phones from. Let’s have a look at the popular ones:

Classified Ads Websites Like Craigslist


Craigslist is a traditional place that lets you find a lot of money-saving deals on used or reconditioned phones. However, it involves the most risk because you are purchasing directly from an individual seller and don’t get any guarantee or return policy. So, be careful in the selection of a seller.

Auction Websites Such as eBay


Millions of people or companies choose eBay for selling their products including mobile phones. You can easily discover various deals on second hand or refurbished smartphones there. Nevertheless, remember that such types of sites don’t examine the phones and many scammers try to sell their second-rated or defective phones as new or reconditioned ones. So, try to avoid potential scams when buying a phone from eBay or any other auction sites.

Online Retail Shops Like Amazon Trade-in and Gazelle


These marketplaces act as mediators between seller and buyer and guarantee the deal. Further, these sites inspect second hand mobile phones before presenting them for sale, therefore, you are certain to get what you are paying for.

Certified Third-Party Dealers/Sellers


Third-party dealers or sellers are typically approved by smartphone manufacturing companies. Such type of marketplaces offer factory-refurbished and fully tested mobile phones. So, you can buy a nearly new phone at a good discount.

If you want to own a used iPhone, you can explore the refurbished iPhone dealers in UK to avail the best ever deals.

3. Is Any Difference Between a Reconditioned or Used Cell Phone?


Yes. Both are typically different from each other. Used phones are generally sold as-is. That means such mobile phone devices don’t get any refurbishment treatment to restore their fresh condition and functionality. Therefore, they have some scratches and signs of usage or damage, but good in performance if you buy from a reputable seller.

Conversely, reconditioned phones are undergone a complete refurbishment treatment to fix any glitches and to restore their fresh look. This is the reason, such mobile phones not only look like new handsets but also work as good as the new ones.

Bear in mind that used smartphones are usually cheaper than refurbished/reconditioned ones.





4. Is the Mobile Phone Unlocked?


If you are going to buy a second hand or reconditioned phone, you should take into account that either it is locked or unlocked. If you get a locked cell phone, it means that you can’t activate it with any carrier of your choice because it would be locked to some particular carriers. So, try to look for an unlocked mobile phone. Unlocked smartphones enable you to use the services of any preferred network service providers on your gadget.

5. Is the Second Hand Phone Stolen?


If you are purchasing a used or refurbished mobile phone from eBay or Craigslist etc. then it is imperative to make sure that the phone is not stolen or blacklisted. A lot of scamming people use these sites to make money by selling those smartphones that are reported as blacklisted by their real owners; that means these phones have been lost or stolen. Keep in mind that blacklisted phones are not usable.

On the other hand, if you head over to a retail site or a certified dealer’s website to buy a second hand phone, they check the serial number and ensure phones are not stolen before selling. But if you are doing a deal on eBay or Craigslist, you are all alone. So, you should ask the IMEI number from the seller to check that the phone is blacklisted or not.

6. What Condition Is the Second Hand or Refurbished Phone In?


Before buying a used or reconditioned phone, it is obvious to make sure what condition is it in. These phones are generally categorised in different Positions, depending on their condition. Pristine, Excellent, Good, Acceptable, and Refurbished are some terms which are ordinarily used to define the condition of used or reconditioned phones.

Hence, some dealers or sellers also categorise used smartphones in different Grades. Grade A phones not only look like new phones but their quality is also much closer to the new ones, while Grade B and C mobile phones might have some scratches, signs, and marks etc.

7. What’s a Used or Reconditioned Phone Worth?


Don’t become a fool by paying more for less. If you are buying a used or reconditioned phone, it is also key to consider its price. Commonly, second hand or refurbished smartphones are low priced, as much as 50% cheaper than their counterparts. However, the prices depend on the make, model, and condition of the phones. So, before getting attracted towards the cheapest price, inspect the phone condition.

Moreover, never choose the first price you get for a second hand handset. Browse multiple deals and compare them to pick up the best one!

8. Do I Get Warranty on My Used or Refurbished Phone?


It is another key question you must consider before getting a used phone. In general, used phones are not covered under warranty but some sellers provide it. Conversely, reconditioned ones are offered with 90-180 days warranty.

Prefer a seller who offers you a decent warranty and money back guarantee whether you are buying a used or refurbished smartphone.

9. Is Now the Right Time to Purchase a Refurbished or Used Smartphone?


Yes, absolutely! Time is money and you can start looking for various deals on used or reconditioned phones available at different shops today. I am sure, you will definitely find the one that fits your needs and budget. However, it is important to take into consideration that when new models come into the market, the prices of previous versions drop down. So, if you are interested in buying an iPhone X or Samsung Galaxy S8, you can get it in a refurbished condition and save hundreds of pounds since the latest Samsung Galaxy S9 has entered into the market and Apple is also going to launch its three new iPhones in a few coming months.