Monday, 17 February 2020

Live Bootstrap 4 Table Row Reorder with PHP using Ajax jQuery

Table Row Reorder is a very important task in web development. For this things here we have make this tutorial, in which we have use Bootstrap 4 Table and we will Reorder Bootstrap 4 Table row reorder by using jQuery UI with Ajax and PHP. Table Row Reorder means, in which order we want to display row in Bootstrap 4 table.

For table row reorder here we will use jQuery UI Drag and Drop feature. jQuery UI Drag and Drop feature is very user friendly which allows to Users to reorder components by drag and drop functionality. That means it will put elements on desired position. If you are developing any web application, in which you have list your data in Bootstrap 4 table, then by using Drag and Drop functionality, we can easily reorder table row data and it will increase our web application user experience. Now in your mind how to enable drag and drop feature, for this we have to use jQuery UI library sortable() plugin. This plugin will enable drap and drop feature to any element.

By using jQuery UI sortable() plugin we can enable dragging and dropping functionality to any element, but after reorder table row, we want to store updated order data in Mysql table also. So when we have refresh web page, then our reorder row data has not be lost. For this we have to store updated order data in Mysql table on every drag and drop event. For update order data in Mysql table, here we will use Ajax request in sortable() method, so when we have drag and drop elements, then it will send Ajax request to PHP script for store order data in Mysql table. Below you can find source code of Live Bootstrap 4 Table row reorder with PHP using jQuery Ajax and Mysql database.



Source Code


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `page`
--

CREATE TABLE `page` (
  `page_id` int(11) NOT NULL,
  `page_title` text NOT NULL,
  `page_url` text NOT NULL,
  `page_order` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `page`
--

INSERT INTO `page` (`page_id`, `page_title`, `page_url`, `page_order`) VALUES
(1, 'JSON - Dynamic Dependent Dropdown List using Jquery and Ajax', 'json-dynamic-dependent-dropdown-list-using-jquery-and-ajax', 3),
(2, 'Live Table Data Edit Delete using Tabledit Plugin in PHP', 'live-table-data-edit-delete-using-tabledit-plugin-in-php', 4),
(3, 'Create Treeview with Bootstrap Treeview Ajax JQuery in PHP\r\n', 'create-treeview-with-bootstrap-treeview-ajax-jquery-in-php', 8),
(4, 'Bootstrap Multiselect Dropdown with Checkboxes using Jquery in PHP\r\n', 'bootstrap-multiselect-dropdown-with-checkboxes-using-jquery-in-php', 10),
(5, 'Facebook Style Popup Notification using PHP Ajax Bootstrap\r\n', 'facebook-style-popup-notification-using-php-ajax-bootstrap', 7),
(6, 'Modal with Dynamic Previous & Next Data Button by Ajax PHP\r\n', 'modal-with-dynamic-previous-next-data-button-by-ajax-php', 5),
(7, 'How to Use Bootstrap Select Plugin with Ajax Jquery PHP\r\n', 'how-to-use-bootstrap-select-plugin-with-ajax-jquery-php', 1),
(8, 'How to Load CSV File data into HTML Table Using AJAX jQuery\r\n', 'how-to-load-csv-file-data-into-html-table-using-ajax-jquery', 2),
(9, 'Autocomplete Textbox using Typeahead with Ajax PHP Bootstrap\r\n', 'autocomplete-textbox-using-typeahead-with-ajax-php-bootstrap', 6),
(10, 'Export Data to Excel in Codeigniter using PHPExcel\r\n', 'export-data-to-excel-in-codeigniter-using-phpexcel', 9);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `page`
--
ALTER TABLE `page`
  ADD PRIMARY KEY (`page_id`);

--
-- AUTO_INCREMENT for dumped tables
--

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


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Live Bootstrap 4 Table Row Reorder with PHP using Ajax jQuery</title>
  <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" type="text/css">
  <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js" integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E=" crossorigin="anonymous"></script>
 </head>
 <body>
  <br />
  <br />
  <div class="container">
   <h3 align="center">Live Bootstrap 4 Table Row Reorder with PHP using Ajax jQuery</h3>
   <br />
   <div class="card">
    <div class="card-header">Live Table Row Reorder</div>
    <div class="card-body">
     <div class="table-resposive">
      <table class="table table-striped table-bordered">
       <thead style="cursor: ">
        <tr>
         <th>Post Name</th>
         <th>Post Order</th>
        </tr>
       </thead>
       <tbody style="cursor: all-scroll;"></tbody>
      </table>
     </div>
    </div>
   </div>
  </div>
 </body>
</html>
<script>
$(document).ready(function(){

 load_data();

 function load_data()
 {
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{action:'fetch_data'},
   dataType:'json',
   success:function(data)
   {
    var html = '';
    for(var count = 0; count < data.length; count++)
    {
     html += '<tr id="'+data[count].page_id+'">';
     html += '<td>'+data[count].page_title+'</td>';
     html += '<td>'+data[count].page_order+'</td>';
     html += '</tr>';
    }
    $('tbody').html(html);
   }
  })
 }

 $('tbody').sortable({
  placeholder : "ui-state-highlight",
  update : function(event, ui)
  {
   var page_id_array = new Array();
   $('tbody tr').each(function(){
    page_id_array.push($(this).attr('id'));
   });

   $.ajax({
    url:"action.php",
    method:"POST",
    data:{page_id_array:page_id_array, action:'update'},
    success:function()
    {
     load_data();
    }
   })
  }
 });

});
</script>


action.php




<?php

//action.php;

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

if(isset($_POST["action"]))
{
 if($_POST["action"] == 'fetch_data')
 {
  $query = "
  SELECT * FROM page 
  ORDER BY page_order ASC
  ";

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

  $statement->execute();

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

  echo json_encode($data);
 }

 if($_POST['action'] == 'update')
 {
  for($count = 0;  $count < count($_POST["page_id_array"]); $count++)
  {
   $query = "
   UPDATE page 
   SET page_order = '".($count+1)."' 
   WHERE page_id = '".$_POST["page_id_array"][$count]."'
   ";
   $statement = $connect->prepare($query);
   $statement->execute();
  }
 }
}

?>






Tuesday, 11 February 2020

Facebook Style Load Data in Timeline with PHP Mysql Ajax



If you have used Social Media website like Facebook, then in that when page has been load in web page then first it has load content loading placeholder and then after it has load content on web page. It has been use Timeline feature of web development for display content on web page. So, when first page has been load then in timeline skeleton first has been load with loading placeholder and then after it has load content on web page. After this when we have scroll web page, then it has again load more data. But before loading of more data on page scroll, first it has load content loading placeholder in timeline, and then after it has load dynamic content in timeline. On every page scroll it has load chunks of records in timeline. This process will be continues, still there is data in database available.

So, in this tutorial, we will make Facebook style timeline content loading placeholder by using PHP script, and then after we will load data on web page by using PHP script with Ajax, Mysql database and jQuery. When we have scroll web page for view more data, then first it has load timeline content loading placeholder by using CSS with jQuery function, and then after by using Ajax it has send request to PHP script for fetch next some records from Mysql Database. This process will continue execute on every page scroll. Once there is no data available in Mysql database then it will display no more data available for display message will be display on web page.

If you are web developer, then you should know "Timeline is a great data visualization tool. It mainly used for display data in more visualize manner. There are many website has been used Timeline feature for display data on web page. Timeline has been provide simple, logical way tell your data on web page. It has represent your data in chronological sequence, which are related to event which has been in particular time line. So, readers can simply understand the relationship of each event when occurs. So, here we have use Timeline concept for load data on web page.

But here we have not use only Timeline concept, but here we have use Pagination feature has been used in different manner. Here we have not make pagination link on web page, but we will chunks of data on every page scroll. So, here we have not load all data at a time in timeline format on web page. But we have load only some data which has been visible on web page. And when we have scroll web page, then next data will be load on web page in timeline. For this load more data on scroll we have use Ajax request for fetch data from web page and display on web page in timeline. So, here we have merge the concept of Timeline, Load more data and content placeholder and make Facebook style load data in Timeline with PHP script, Mysql database, Ajax and jQuery. Below you can find complete source code.







Source Code


index.php



<!DOCTYPE html>
<html>
  <head>
    <title>Facebook Style Load Data in Timeline with PHP Mysql Ajax</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/placeholder-loading/dist/css/placeholder-loading.min.css">
    <style>
    .timeline {
      list-style: none;
      padding: 20px 0 20px;
      position: relative;
    }
    .timeline:before {
      top: 0;
      bottom: 0;
      position: absolute;
      content: " ";
      width: 3px;
      background-color: #eeeeee;
      left: 50%;
      margin-left: -1.5px;
    }
    .timeline > li {
      margin-bottom: 20px;
      position: relative;
      width: 50%;
      float: left;
      clear: left;
    }
    .timeline > li:before,
    .timeline > li:after {
      content: " ";
      display: table;
    }
    .timeline > li:after {
      clear: both;
    }
    .timeline > li:before,
    .timeline > li:after {
      content: " ";
      display: table;
    }
    .timeline > li:after {
      clear: both;
    }
    .timeline > li > .timeline-panel {
      width: 95%;
      float: left;
      border: 1px solid #d4d4d4;
      /*border-radius: 2px;*/
      /*padding: 20px;*/
      position: relative;
      -webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
      box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
    }

    .timeline > li > .timeline-panel:before {
      position: absolute;
      top: 26px;
      right: -15px;
      display: inline-block;
      border-top: 15px solid transparent;
      border-left: 15px solid #ccc;
      border-right: 0 solid #ccc;
      border-bottom: 15px solid transparent;
      content: " ";
    }
    .timeline > li > .timeline-panel:after {
      position: absolute;
      top: 27px;
      right: -14px;
      display: inline-block;
      border-top: 14px solid transparent;
      border-left: 14px solid #fff;
      border-right: 0 solid #fff;
      border-bottom: 14px solid transparent;
      content: " ";
    }
    .timeline > li > .timeline-badge {
      color: #fff;
      width: 24px;
      height: 24px;
      line-height: 50px;
      font-size: 1.4em;
      text-align: center;
      position: absolute;
      top: 16px;
      right: -12px;
      /*background-color: #999999;*/
      z-index: 100;
      /*
      border-top-right-radius: 50%;
      border-top-left-radius: 50%;
      border-bottom-right-radius: 50%;
      border-bottom-left-radius: 50%;
      */
    }
    .timeline > li.timeline-inverted > .timeline-panel {
      float: right;
    }
    .timeline > li.timeline-inverted > .timeline-panel:before {
      border-left-width: 0;
      border-right-width: 15px;
      left: -15px;
      right: auto;
    }
    .timeline > li.timeline-inverted > .timeline-panel:after {
      border-left-width: 0;
      border-right-width: 14px;
      left: -14px;
      right: auto;
    }
    .timeline-badge > a {
      color: #C5C7C5 !important;
    }
    .timeline-badge a:hover {
      color: #000 !important;
    }
    .timeline-title {
      margin-top: 0;
      color: inherit;
    }
    .timeline-body{
        padding:15px;
    }
    .timeline-body > h1{
        font-size:22px;
    }
    .timeline-body > h2{
        font-size: 18px;
        font-weight: 700;
        margin:0;
    }
    .timeline-body > p,
    .timeline-body > ul {
        /*padding:20px;
        margin-bottom: 0;*/
        padding:0;
        margin-bottom: 10px;
    }
    .timeline-body > p + p {
      margin-top: 5px;
    }
    .timeline-footer{
        padding:20px;
        background-color:#f4f4f4;
    }
    .timeline-footer > a{
        cursor: pointer;
        text-decoration: none;
    }

    .timeline > li.timeline-inverted{
      float: right; 
      clear: right;
      margin-top: 30px;
      margin-bottom: 30px;
    }
    .timeline > li:nth-child(2){
      margin-top: 60px;
    }
    .timeline > li.timeline-inverted > .timeline-badge{
      left: -12px;
    }

    @media (max-width: 767px) {
        ul.timeline:before {
            left: 40px;
        }

        ul.timeline > li {
          margin-bottom: 20px;
          position: relative;
          width:100%;
          float: left;
          clear: left;
        }
        ul.timeline > li > .timeline-panel {
            width: calc(100% - 90px);
            width: -moz-calc(100% - 90px);
            width: -webkit-calc(100% - 90px);
        }

        ul.timeline > li > .timeline-badge {
            left: 28px;
            margin-left: 0;
            top: 16px;
        }

        ul.timeline > li > .timeline-panel {
            float: right;
        }

        ul.timeline > li > .timeline-panel:before {
          border-left-width: 0;
          border-right-width: 15px;
          left: -15px;
          right: auto;
        }

        ul.timeline > li > .timeline-panel:after {
          border-left-width: 0;
          border-right-width: 14px;
          left: -14px;
          right: auto;
        }
        
      .timeline > li.timeline-inverted{
        float: left; 
        clear: left;
        margin-top: 30px;
        margin-bottom: 30px;
      }

      .timeline > li.timeline-inverted > .timeline-badge{
        left: 28px;
      }
    }
    </style>
  </head>
  <body>
    <br />
    <div class="container">
      <h3 align="center">Facebook Style Load Data in Timeline with PHP Mysql Ajax</h3>
      <br />
      <div class="card">
        <div class="card-header">Dynamic Data</div>
        <div class="card-body">
          <ul class="timeline">

            <li class="clearfix" id="clearfix_id" style="float: none;"></li>
          </ul>
          <span id="no_more_data"></span>
        </div>
      </div>
      <br />
      <br />
    </div>
  </body>
</html>
<script>
  $(document).ready(function(){

    var action = 'inactive';

    function load_timeline_data(last_id = '')
    {      
      $.ajax({
        url:"fetch.php",
        method:"POST",
        data:{last_id:last_id},
        dataType:'json',
        success:function(data)
        {
          setTimeout(function(){
            $('.removeTimeline').remove();
            $('#clearfix_id').remove();
            $('.timeline').append(data.timeline_output);
            if(data.no_data_output != '')
            {
              $('#no_more_data').html(data.no_data_output);
            }
            action = 'inactive';
          }, 1000);
        }
      });
    }

    function make_skeleton()
    {
      var output = '';
      $('#clearfix_id').remove();
      for(var count = 0; count < 4; count++)
      {
        temporary_class = '';
        if(count%2 != 0)
        {
          temporary_class = 'class="timeline-inverted removeTimeline"';
        }
        else
        {
          temporary_class = 'class="removeTimeline"';
        }

        output += '<li '+temporary_class+'>';
        output += '<div class="timeline-badge primary"><a><i class="fa fa-dot-circle-o" aria-hidden="true"></i></a></div>';
        output += '<div class="timeline-panel">';
        output += '<div class="timeline-heading"></div>';
        output += '<div class="timeline-body">';
        output += '<div class="ph-item">';
        output += '<div class="ph-col-4">';
        output += '<div class="ph-picture"></div>';
        output += '</div>';
        output += '<div>';
        output += '<div class="ph-row">';
        output += '<div class="ph-col-12 big"></div>';
        output += '<div class="ph-col-12"></div>';
        output += '<div class="ph-col-12"></div>';
        output += '<div class="ph-col-12"></div>';
        output += '<div class="ph-col-12"></div>';
        output += '</div></div></div>';
        output += '</div>';
        output += '</div></div></li>';
      }
      output += '<li class="clearfix" id="clearfix_id" style="float: none;"></li>';
      $('.timeline').append(output);
    }

    if(action == 'inactive')
    {
      make_skeleton();

      setTimeout(function(){ 
        load_timeline_data(); 
      }, 3000);
    }

    $(window).scroll(function(){
      var last_id = $('#clearfix_id').data('last_id');
      if(last_id != '')
      {
        if($(window).scrollTop() + $(window).height() > $(".timeline").height() && action == 'inactive')
        {
          action = 'active';
          make_skeleton();

          setTimeout(function(){ 
            load_timeline_data(last_id); 
          }, 5000);
        }
      }
    });

  });
</script>





fetch.php



<?php

//fetch.php;

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

if(isset($_POST["last_id"]))
{
 //sleep(5);
 if($_POST["last_id"] != '')
 {
  $query = "
  SELECT * FROM tbl_post 
  WHERE id < '".$_POST["last_id"]."'
  ORDER BY id DESC 
  LIMIT 4
  ";
 }
 else
 {
  $query = "
  SELECT * FROM tbl_post 
  ORDER BY id DESC 
  LIMIT 4
  ";
 }

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

 $statement->execute();

 $total_row = $statement->rowCount();

 $output = '';
 $not_found = '';
 $last_id = 0;
 if($total_row > 0)
 {
  $result = $statement->fetchAll();
  $count = 0;
  $class = '';
  foreach($result as $row)
  {   
   if($count%2 != 0)
   {
    $class = 'class="timeline-inverted"';
   }
   else
   {
    $class = '';
   }
   $output .= '
   <li '.$class.'>
    <div class="timeline-badge primary"><a><i class="fa fa-dot-circle-o" aria-hidden="true"></i></a></div>
    <div class="timeline-panel">
     <div class="timeline-heading">
      <div class="col-md-12" style="padding:15px; background-color:#eee; border-bottom:#ddd 1px solid;"><h3>'.$row["post_title"].'</h3></div>
     </div>
     <div class="timeline-body">
      <div class="row">
       <div class="col-md-4">
        <img src="images/'.$row["post_image"].'" class="img-thumbnail img-fluid" />
       </div>
       <div class="col-md-8">
        <p>'.$row["post_description"].'</p>
       </div>
      </div>
     </div>
    </div>
   </li>';
   $last_id = $row["id"];
   $count++;
  }
 }
 else
 {
  $not_found = '
  <div align="center" class="alert alert-info">No more data found</div>
  ';
 }

 $output .= '<li class="clearfix" id="clearfix_id" data-last_id="'.$last_id.'" style="float: none;"></li>';

 $test_output = array(
  'timeline_output' => $output,
  'no_data_output' => $not_found
 );

 echo json_encode($test_output);
}

?>


If you have follow above source code, then you can build Facebook style Load content placeholder in Timeline and then after some time it will load data by using PHP script with Ajax. If you want to get complete source code file, you can email us at webslesson@gmail.com.

Tuesday, 4 February 2020

Instant Search with Pagination in PHP Mysql jQuery and Ajax



If you looking for tutorial on Ajax Live Data Search with Pagination in PHP Mysql using Ajax, then you have land on right page. Because in this post, we have make tutorial on Instant Mysql Data search with Pagination feature by using PHP script with Ajax and jQuery. If you are using PHP for you web development, then you have know Data Search and Pagination, both are required functionality of any web based application. So, you have to learn both things, because Search and Pagination both are used in most of the PHP based web application.

In Web development, Search is the most powerful functionality in the Mysql Database management section. And if Search functionality is live or instant, then you can quickly ge the filter data from the large amount of data. If you are User then you can get the relevant set of data from the large list of records in a seconds. For make live search feature, here we have use Ajax with PHP script. So, we can get the filter data on web page without refresh of web page. So, by using Ajax with PHP script we can easily implement Live search functionality for our PHP based web application.

If we have use Live search feature in our web application, then there is large amount of data has been filter from Mysql database, then on single web page we have load large filter data, then it will slow down our application. For prevent loading of large filter data on single web page, here we have use the Pagination functionality of web development. Here we will implement pagination without page refresh, because here also for Pagination we will use Ajax with PHP script. So we can easily implement Ajax pagination with PHP script. If we have use Ajax Pagination, then it will make the list of data more user friendly. In this post, we will implement Ajax Live Search with Pagination feature in PHP application. Below you can find the complement source of code this tutorial.






Source Code


index.php



<!DOCTYPE html>
<html>
  <head>
    <title>Live Data Search with Pagination in PHP using Ajax</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
    <link rel="stylesheet" href="https://unpkg.com/placeholder-loading/dist/css/placeholder-loading.min.css">
  </head>
  <body>
    <br />
    <div class="container">
      <h3 align="center">Live Data Search with Pagination in PHP Mysql using Ajax</h3>
      <br />
      <div class="card">
        <div class="card-header">Dynamic Data</div>
        <div class="card-body">
          <div class="form-group">
            <input type="text" name="search_box" id="search_box" class="form-control" placeholder="Type your search query here" />
          </div>
          <div class="table-responsive" id="dynamic_content">
            
          </div>
        </div>
      </div>
    </div>
  </body>
</html>
<script>
  $(document).ready(function(){

    load_data(1);

    function load_data(page, query = '')
    {
      $.ajax({
        url:"fetch.php",
        method:"POST",
        data:{page:page, query:query},
        success:function(data)
        {
          $('#dynamic_content').html(data);
        }
      });
    }

    $(document).on('click', '.page-link', function(){
      var page = $(this).data('page_number');
      var query = $('#search_box').val();
      load_data(page, query);
    });

    $('#search_box').keyup(function(){
      var query = $('#search_box').val();
      load_data(1, query);
    });

  });
</script>





fetch.php



<?php

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

/*function get_total_row($connect)
{
  $query = "
  SELECT * FROM tbl_webslesson_post
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  return $statement->rowCount();
}

$total_record = get_total_row($connect);*/

$limit = '5';
$page = 1;
if($_POST['page'] > 1)
{
  $start = (($_POST['page'] - 1) * $limit);
  $page = $_POST['page'];
}
else
{
  $start = 0;
}

$query = "
SELECT * FROM tbl_webslesson_post 
";

if($_POST['query'] != '')
{
  $query .= '
  WHERE webslesson_post_title LIKE "%'.str_replace(' ', '%', $_POST['query']).'%" 
  ';
}

$query .= 'ORDER BY webslesson_post_id ASC ';

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

$statement = $connect->prepare($query);
$statement->execute();
$total_data = $statement->rowCount();

$statement = $connect->prepare($filter_query);
$statement->execute();
$result = $statement->fetchAll();
$total_filter_data = $statement->rowCount();

$output = '
<label>Total Records - '.$total_data.'</label>
<table class="table table-striped table-bordered">
  <tr>
    <th>ID</th>
    <th>Post Title</th>
  </tr>
';
if($total_data > 0)
{
  foreach($result as $row)
  {
    $output .= '
    <tr>
      <td>'.$row["webslesson_post_id"].'</td>
      <td>'.$row["webslesson_post_title"].'</td>
    </tr>
    ';
  }
}
else
{
  $output .= '
  <tr>
    <td colspan="2" align="center">No Data Found</td>
  </tr>
  ';
}

$output .= '
</table>
<br />
<div align="center">
  <ul class="pagination">
';

$total_links = ceil($total_data/$limit);
$previous_link = '';
$next_link = '';
$page_link = '';

//echo $total_links;

if($total_links > 4)
{
  if($page < 5)
  {
    for($count = 1; $count <= 5; $count++)
    {
      $page_array[] = $count;
    }
    $page_array[] = '...';
    $page_array[] = $total_links;
  }
  else
  {
    $end_limit = $total_links - 5;
    if($page > $end_limit)
    {
      $page_array[] = 1;
      $page_array[] = '...';
      for($count = $end_limit; $count <= $total_links; $count++)
      {
        $page_array[] = $count;
      }
    }
    else
    {
      $page_array[] = 1;
      $page_array[] = '...';
      for($count = $page - 1; $count <= $page + 1; $count++)
      {
        $page_array[] = $count;
      }
      $page_array[] = '...';
      $page_array[] = $total_links;
    }
  }
}
else
{
  for($count = 1; $count <= $total_links; $count++)
  {
    $page_array[] = $count;
  }
}

for($count = 0; $count < count($page_array); $count++)
{
  if($page == $page_array[$count])
  {
    $page_link .= '
    <li class="page-item active">
      <a class="page-link" href="#">'.$page_array[$count].' <span class="sr-only">(current)</span></a>
    </li>
    ';

    $previous_id = $page_array[$count] - 1;
    if($previous_id > 0)
    {
      $previous_link = '<li class="page-item"><a class="page-link" href="javascript:void(0)" data-page_number="'.$previous_id.'">Previous</a></li>';
    }
    else
    {
      $previous_link = '
      <li class="page-item disabled">
        <a class="page-link" href="#">Previous</a>
      </li>
      ';
    }
    $next_id = $page_array[$count] + 1;
    if($next_id >= $total_links)
    {
      $next_link = '
      <li class="page-item disabled">
        <a class="page-link" href="#">Next</a>
      </li>
        ';
    }
    else
    {
      $next_link = '<li class="page-item"><a class="page-link" href="javascript:void(0)" data-page_number="'.$next_id.'">Next</a></li>';
    }
  }
  else
  {
    if($page_array[$count] == '...')
    {
      $page_link .= '
      <li class="page-item disabled">
          <a class="page-link" href="#">...</a>
      </li>
      ';
    }
    else
    {
      $page_link .= '
      <li class="page-item"><a class="page-link" href="javascript:void(0)" data-page_number="'.$page_array[$count].'">'.$page_array[$count].'</a></li>
      ';
    }
  }
}

$output .= $previous_link . $page_link . $next_link;
$output .= '
  </ul>

</div>
';

echo $output;

?>


By follow Source code of Ajax Live Mysql Data Search with Pagination using PHP script, then you can definately build or PHP Ajax Live Search box for you web application and if you still want to get any assistance, then you can email us at webslesson@gmail.com.




Monday, 27 January 2020

Building Skeleton Loading Effect in PHP with Ajax



Currently, On many social media website Youtube or Facebook, we can see when page has been load in browser, then before loading of data on web page, we can see loading data skeleton has been first seen on web page and then after some seconds of time data has been load on web page. So, in this post we are going to make this type of skeleton loading screen by using Bootstrap library and by using PHP script with Ajax jquery we will load data on web page. Here from make Skeleton Loader we will not use any jQeury plugin but we will use simple CSS for creating Skeleton loading screen.

In this tutorial, we will make Skeleton Loader with Bootstrap. For this we have use this gitup code. This placeholder loading code, there is only CSS has been used for make content placeholder loading with animation effect. By using this style sheet we can make simple and flexible content placeholder loading skeleton with animation effect. This library is very easy to use, you have to simple stylesheet url in header of your web page and you can make skeleton screen in you web page by using css class of this library.

So, If you are looking for web tutorial for building Facebook or Youtube style content placeholder or data loading skeleton for your web page. Then this post will help you to make Facebook or Youtube style data load skeleton screen in simple steps. Here we have make data load skeleton loader by using placeholder loading style sheet library with Bootstrap. This skeleton loader we can use as web page loading progress which will look like Facebook like data loader, or YouTube like video thumbnail loader, or even you can also use as custom image loader or content loader also. After displaying data skeleton loader, and for load original data here we have use PHP script with Ajax. So, For source code of developing data load skeleton screen load with Bootstrap and for load data with PHP script with Ajax jQuery. Then below you can find complete source code.




Source Code


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_post`
--

CREATE TABLE `tbl_post` (
  `id` mediumint(8) UNSIGNED NOT NULL,
  `post_title` text,
  `post_description` text,
  `author` varchar(255) DEFAULT NULL,
  `datetime` datetime DEFAULT NULL,
  `post_image` varchar(150) DEFAULT NULL,
  `post_url` varchar(150) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_post`
--
ALTER TABLE `tbl_post`
  MODIFY `id` mediumint(8) UNSIGNED NOT NULL AUTO_INCREMENT;



index.php



<!DOCTYPE html>
<html>
  <head>
    <title>Make Skeleton Loader with PHP Ajax using Bootstrap</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
    <link rel="stylesheet" href="https://unpkg.com/placeholder-loading/dist/css/placeholder-loading.min.css">
  </head>
  <body>
    <br />
    <div class="container">
      <h3 align="center">Make Skeleton Loader with PHP Ajax using Bootstrap</h3>
      <br />
      <div class="card">
        <div class="card-header">Dynamic Data</div>
        <div class="card-body" id="dynamic_content">
          
        </div>
      </div>
    </div>
  </body>
</html>
<script>
  $(document).ready(function(){

    $('#dynamic_content').html(make_skeleton());

    setTimeout(function(){
      load_content(5);
    }, 5000);

    function make_skeleton()
    {
      var output = '';
      for(var count = 0; count < 5; count++)
      {
        output += '<div class="ph-item">';
        output += '<div class="ph-col-4">';
        output += '<div class="ph-picture"></div>';
        output += '</div>';
        output += '<div>';
        output += '<div class="ph-row">';
        output += '<div class="ph-col-12 big"></div>';
        output += '<div class="ph-col-12"></div>';
        output += '<div class="ph-col-12"></div>';
        output += '<div class="ph-col-12"></div>';
        output += '<div class="ph-col-12"></div>';
        output += '</div>';
        output += '</div>';
        output += '</div>';
      }
      return output;
    }

    function load_content(limit)
    {
      $.ajax({
        url:"fetch.php",
        method:"POST",
        data:{limit:limit},
        success:function(data)
        {
          $('#dynamic_content').html(data);
        }
      })
    }

  });
</script>





fetch.php



<?php

//fetch.php;

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

if(isset($_POST['limit']))
{
 $query = "
 SELECT * FROM tbl_post 
 ORDER BY id DESC 
 LIMIT ".$_POST["limit"]."
 ";

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

 $statement->execute();

 $result = $statement->fetchAll();

 $output = '';

 foreach($result as $row)
 {
  $output .= '
  <div class="row">
   <div class="col-md-4">
    <img src="images/'.$row["post_image"].'" class="img-thumbnail" />
   </div>
   <div class="col-md-8">
    <h2><a href="'.$row["post_url"].'">'.$row["post_title"].'</a></h2>
    <br />
    <p>'.$row["post_description"].'</p>
   </div>
  </div>
  <hr />
  ';
 }

 echo $output;
}

?>



Sunday, 19 January 2020

How to Create AutoComplete Textbox using PHP with jQuery Ajax



Do you know what is AutoSuggest or AutoComplete textbox? The AutoSuggest Textbox means when user has type in search textbox, then they can get quickly get result according what they has type in search box, and they can select value form pre populated search suggestion from the list. This AutoSuggestion feature will load suggestion automatically, when user has type some character into Search textbox field. Here we will make lightweight AutoSuggest or AutoComplete textbox by using PHP script with Mysql Database, jQuery and Ajax.

Now in your mind one question will arise, How it called light weight AutoSuggest Textbox. This is because here when user has type in search textbox, then it will only one time fetch data from Mysql database, and then after by using jQuery plugin it will filter data from data which has fetch from database and display filter result in AutoSuggest search result. So, Here we have called this light weight AutoSuggest or AutoComplete Textbox, because it is only send one request to Mysql database and fetch data and by using jQuery plugin it has filter result from that data and display as AutoSuggest result below Search box.

In Most of AutoComplete or AutoSuggest tutorial, we have seen on every character type, it has send request to Mysql database using Ajax and display search result, but In this tutorial, it will only send one Ajax request to Mysql database and then after data will be filter by using jQuery and display one web page. For make this tutorial, here we have use jQuery "JsLocalSearch" plugin, which is very light weight and fast jquery plugin, which used for filter records from client side data and which is mainly used for filter and search a of element which we have provide. It main feature is to search html content which we have provide. Below you can find source code of How to make AutoSuggest Textbox with Bootstrap library by using PHP script with jQuery Ajax and Mysql database.







Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `customer_table`
--

CREATE TABLE `customer_table` (
  `customer_id` int(11) NOT NULL,
  `customer_first_name` varchar(200) NOT NULL,
  `customer_last_name` varchar(200) NOT NULL,
  `customer_email` varchar(300) NOT NULL,
  `customer_gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `customer_table`
--
ALTER TABLE `customer_table`
  ADD PRIMARY KEY (`customer_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `customer_table`
--
ALTER TABLE `customer_table`
  MODIFY `customer_id` int(11) NOT NULL AUTO_INCREMENT;





index.php



<!DOCTYPE html>
<html>
 <head>
  <title>jQuery Auto Suggest Textbox with Bootstrap 4 using PHP Ajax</title>
  <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
  <script src="JsLocalSearch.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
  <style> 
  .mark {
    background-color: #d7ffe7 !important
  }

  .mark .gsearch{
    font-size: 20px
  }

  .unmark {
    background-color: #e8e8e8 !important
  }

  .unmark .gsearch{
    font-size: 10px
  }
  
  .marktext
  {
   font-weight:bold;
   background-color: antiquewhite;
  }
  </style>
 </head>
 <body>
  <br />
  <br />
  <div class="container">
   <h3 align="center">jQuery Auto Suggest Textbox with Bootstrap 4 using PHP Ajax</h3>
   <br />
   <br />
   <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-6">
     <input type="text" id="gsearchsimple" class="form-control input-lg" placeholder="Search..." />

     <ul class="list-group">

     </ul>
     <div id="localSearchSimple"></div>
     <div id="detail" style="margin-top:16px;"></div>
    </div>
    <div class="col-md-3"></div>
   </div>
  </div>
 </body>
</html>
<script>
$(document).ready(function(){
 $('#gsearchsimple').keyup(function(){
  var query = $('#gsearchsimple').val();
  $('#detail').html('');
  $('.list-group').css('display', 'block');
  if(query.length == 2)
  {
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{query:query},
    success:function(data)
    {
     $('.list-group').html(data);
    }
   })
  }
  if(query.length == 0)
  {
   $('.list-group').css('display', 'none');
  }
 });

 $('#localSearchSimple').jsLocalSearch({
  action:"Show",
  html_search:true,
  mark_text:"marktext"
 });

 $(document).on('click', '.gsearch', function(){
  var email = $(this).text();
  $('#gsearchsimple').val(email);
  $('.list-group').css('display', 'none');
  $.ajax({
   url:"fetch.php",
   method:"POST",
   data:{email:email},
   success:function(data)
   {
    $('#detail').html(data);
   }
  })
 });
});
</script>


fetch.php



<?php

//fetch.php;

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

if(isset($_POST['query']))
{
 $query = "
 SELECT DISTINCT customer_email FROM customer_table 
 WHERE customer_email LIKE '%".trim($_POST["query"])."%'
 ";

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

 $statement->execute();

 $result = $statement->fetchAll();

 $output = '';

 foreach($result as $row)
 {
  $output .= '
  <li class="list-group-item contsearch">
   <a href="javascript:void(0)" class="gsearch" style="color:#333;text-decoration:none;">'.$row["customer_email"].'</a>
  </li>
  ';
 }

 echo $output;
}

if(isset($_POST['email']))
{
 $query = "
 SELECT * FROM customer_table 
 WHERE customer_email = '".trim($_POST["email"])."' 
 LIMIT 1
 ";

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

 $statement->execute();

 $result = $statement->fetchAll();

 $output = '
 <table class="table table-bordered table-striped">
  <tr>
   <th>First Name</th>
   <th>Last Name</th>
   <th>Email</th>
   <th>Gender</th>
  </tr>
 ';

 foreach($result as $row)
 {
  $output .= '
  <tr>
   <td>'.$row["customer_first_name"].'</td>
   <td>'.$row["customer_last_name"].'</td>
   <td>'.$row["customer_email"].'</td>
   <td>'.$row["customer_gender"].'</td>
  </tr>
  ';
 }
 $output .= '</table>';

 echo $output;
}

?>


So, If you have follow above source code, then you can learn How to Create Light Weight dynamic AutoSuggest or AutoComplete Textbox by using PHP script with Mysql database, jQuery and Ajax. If you want to get this tutorial source code file in zip folder, you can email us at webslesson@gmail.com.

Sunday, 12 January 2020

Laravel 6 - Crop & Upload Image using jQuery with Ajax



Are you a learner of Laravel framework for web application development, So here in this post, you can find interesting topic like How to Crop an Image before uploading in Laravel framework. Here we have use Laravel 6 framework for make this type of feature in any web based application. If you want to learn How to Crop and Upload image in Laravel 6 framework by using jQuery with Ajax, so this post will help you to learn this topic.

Here we have use jQuery Croppie plugin used for Crop an Image before upload it. There are many jQuery plugin are available on internet for Crop image, but here we have use Croppie plugin with Laravel 6 framework for Crop image. Because it is widely used for Crop image, and it is easy to learn How to crop image. So, If you want to add feature like image crop for your web application, so you can use this plugin, because it is very easy to integrate in our web application.

In short, In this post we have use jQuery plugin for Crop an Image and by using Ajax we have upload on web server with Laravel 6 framework. Now in your mind how this Croppie plugin has work. So when page has been load into web browser, then this Croppie plugin has been initialize and once we have select image from our local computer then that selected image preview, we can see on web page. In that preview we can also zoom image, and we can drag the view port of the crop area also. So, this tutorial, you can find step by step process for How to Crop image by using Croppie plugin, and then after how to use Ajax for upload cropped image with Laravel 6 framework.

  • Download and Install Laravel 6 Framework
  • Create Controller Class
  • Create View Blade File
  • Set Route
  • Run Laravel 6 Application


Download and Install Laravel 6 Framework


If you want to use Laravel framework for you any web development task, so first you have to download and installed it in you local computer. For download Laravel 6 framework you have to go command prompt and go to directory in which you want to download Laravel framework, and after this you have to run following command in command prompt.


composer create-project --prefer-dist laravel/laravel laravel6


This command will make laravel6 folder and under this it will download Laravel 6 framework.




Create Controller Class


After download Laravel framework, so you are ready to use Laravel for web development. Here first we want to make Controller class for handle browser http request.So, for create Controller class we have to go command prompt and run following command

//Code
This command will make ImageCropController.php file in app/Http/Controllers folder. In this class we have make following method.

index() - This is the root method of this ImageCropController.php controller class. This method has load view file in browser.

upload() - This method has recieved Ajax request for upload Crop image. This method has received in image in binary string. By using base64_decode() method it will convert binary string to image format and by using file_put_contents() function image will be uploaded in crop_image folder. And lastly send response to Ajax request in Ajax format.

app/Http/Controllers/ImageCropController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageCropController extends Controller
{
    function index()
    {
     return view('image_crop');
    }

    function upload(Request $request)
    {
     if($request->ajax())
     {
      $image_data = $request->image;
      $image_array_1 = explode(";", $image_data);
      $image_array_2 = explode(",", $image_array_1[1]);
      $data = base64_decode($image_array_2[1]);
      $image_name = time() . '.png';
      $upload_path = public_path('crop_image/' . $image_name);
      file_put_contents($upload_path, $data);
      return response()->json(['path' => '/crop_image/' . $image_name]);
     }
    }
}



Create View Blade File


In Laravel framework, View Blade file has been used for display HTML output on web page. View file has been store under resources/views folder. Here we have make image_crop.blade.php file for this tutorial. In this file we have use Croppie plugin, Bootstrap library and jquery library.

resources/views/image_crop.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>How to Crop And Upload Image in Laravel 6 using jQuery Ajax</title>
  <script src="{{ asset('js/jquery.min.js') }}"></script>
  <link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}" />
    <link rel="stylesheet" href="{{ asset('css/croppie.min.css') }}" />
  <!--<script src="{{ asset('js/bootstrap.min.js') }}"></script>!-->
    <script src="{{ asset('js/croppie.min.js') }}"></script>
 </head>
 <body>
  <div class="container">    
    <br />
        <h3 align="center">How to Crop And Upload Image in Laravel 6 using jQuery Ajax</h3>
      <br />
      <div class="card">
        <div class="card-header">Crop and Upload Image</div>
        <div class="card-body">
          <div class="form-group">
            @csrf
            <div class="row">
              <div class="col-md-4" style="border-right:1px solid #ddd;">
                <div id="image-preview"></div>
              </div>
              <div class="col-md-4" style="padding:75px; border-right:1px solid #ddd;">
                <p><label>Select Image</label></p>
                <input type="file" name="upload_image" id="upload_image" />
                <br />
                <br />
                <button class="btn btn-success crop_image">Crop & Upload Image</button>
              </div>
              <div class="col-md-4" style="padding:75px;background-color: #333">
                <div id="uploaded_image" align="center"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <br />
          <br />
          
          <br />
          <br />
    </div>
 </body>
</html>

<script>  
$(document).ready(function(){
  
  $image_crop = $('#image-preview').croppie({
    enableExif:true,
    viewport:{
      width:200,
      height:200,
      type:'circle'
    },
    boundary:{
      width:300,
      height:300
    }
  });

  $('#upload_image').change(function(){
    var reader = new FileReader();

    reader.onload = function(event){
      $image_crop.croppie('bind', {
        url:event.target.result
      }).then(function(){
        console.log('jQuery bind complete');
      });
    }
    reader.readAsDataURL(this.files[0]);
  });

  $('.crop_image').click(function(event){
    $image_crop.croppie('result', {
      type:'canvas',
      size:'viewport'
    }).then(function(response){
      var _token = $('input[name=_token]').val();
      $.ajax({
        url:'{{ route("image_crop.upload") }}',
        type:'post',
        data:{"image":response, _token:_token},
        dataType:"json",
        success:function(data)
        {
          var crop_image = '<img src="'+data.path+'" />';
          $('#uploaded_image').html(crop_image);
        }
      });
    });
  });
  
});  
</script>


Set Route


In Laravel framework, we have to set the route of Controller class method. For this we have to open routes/web.php. In this file we have to set the route of this Controller class method.

routes/web.php

Route::get('image_crop','ImageCropController@index');

Route::post('image_crop/upload', 'ImageCropController@upload')->name('image_crop.upload');


Run Laravel Application


For Run Laravel web application, we have to go command prompt and write following command.


php artisan serve


This command will start Laravel server and give you Laravel application base url. For check above code, you to enter http://127.0.0.1:8000/image_crop url, then after you can check above code. So, this is complete step by step process of image preview for crop image using jQuery Croppie plugin before uploading of image by using Ajax in Laravel 6 framework. If you want to get complete source code file, you can free email us at webslesson@gmail.com. We will send you source code file in zip folder.


Monday, 6 January 2020

Laravel 6 - Store & Retrieve Images From Mysql Database



Storing of Images into Mysql Database and then after fetch images from Mysql database in Laravel framework is one task for any web developer. And in this post, we are going to learn how to store image and retrieve images from MySql database, we will learn this things in Laravel 6 framework. Because this is latest version of Laravel framework, and every learner want to learn any topic in latest version. So In Laravel 6 framework, how to insert images in Mysql database, and then after how to fetch images from Mysql database and display on web page.

In this post, we have step by step describe the process of insert images in Mysql table in Laravel 6 framework. Now in your mind one question has been arise, why we have to store images in database. This is because we can store images in folder, so why we have to store images in database and why we have increase the size of our database. But there is also some advantage of storing or inserting images into database also. There is one important advantage is that when we have take the back up of our database, then at the time all our images or file backup has been also take place and we do not want to take back up of images separately.

There is other benefits of store images in database is that all images has been store in binary form, and it will be visible on web page only. So, here our images has been secured because it is store in binary form not in it's original form. So there are many other benefits of storing images in database. Here in this post we have not discuss benefits of storing images in database, but here we want to discuss what is the process of store and retrieve images from Mysql database in Laravel 6 framework.



  1. Install Laravel 6 framework
  2. Make Database Connection
  3. Create Model Class
  4. Download Image Intervention Library
  5. Create Controller Class
  6. Create View Blade File
  7. Set Route
  8. Run Laravel Application

Install Laravel 6 framework


If you want to use Laravel for you web application development. For this first we want to download Laravel latest version. For this you have to go command prompt and go to directory in which you want to download and Install Laravel framework and run following command.


composer create-project --prefer-dist laravel/laravel laravel6


This command will make laravel6 folder and in that folder it will download latest version of Laravel framework.

Make Database Connection


For make database connection in Laravel 6 framework, we have to open .env file. In this file we have to define Mysql database configuration details, which you can find below.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Create Model Class


For store and retrieve image from Mysql database, here we will use Laravel Model class for database related operation. So, first we want to make Model class, for this we have to go command prompt and run following command.


php artisan make:model Images -m


This command will make Images.php model class in app directory and also make table migrations file in database/migrations folder. First we have to open migration file which you can find database/migrations folder and in that you to define table column defination which you can find below.


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('user_name');
            $table->binary('user_image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}



Here we have add two table column like user_name and user_image. Now we want to create table in mysql database. For this also we have to go command prompt and run following command.


php artisan migrate


This command will make images table in Mysql database. Now we open app/Images.php model class. In this class we have to define in which table column data, will be fill be user, we have to define in model class, which you can find below.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Images extends Model
{
    protected $fillable = ['user_name', 'user_image'];
}



Download Image Intervention Library


Here we have use Image Intervention library for Image manipulation. This library is open source PHP image library for handling and manipulation of Image, this library has also provide feature like create, edit and compose image. First we want to download this library, for this we have to run following command.


composer require intervention/image


This command will download this image intervention library, here we have use extra package in Laravel framework, so we have to tell laravel for this new package. For this we have to open config/app.php and define new package details.


'providers' => [

    // ...
      Intervention\Image\ImageServiceProvider::class,
    // ...
  ],
'aliases' => [
    // ...
      'Image'     => Intervention\Image\Facades\Image::class,
    // ...
  ],


So, this way we can use extra package in Laravel fraework.



Create Controller Class


In Laravel framework for handle http request, we have to create controller class. For create controller class file we have to go command prompt and run following command.


php artisan make:controller StoreImageController


This command will make StoreImageController.php controller file under app/Http/Controllers folder. In this controller class, first we have to import following class in header of this class.


use Illuminate\Support\Facades\Response;
use App\Images;
use Image;



After this in controller class we have make following method.

index() - This is the root method of this class, It will fetch data from images folder and display on store_image.blade.php file.

insert_image(Request $request) - When form has been submitted, then this method has received form data for insert data into Mysql database. In this method first it validate that data follow validation rules or not. If it follow validation rules then it has process for insert into mysql table. Here for before store image into Mysql database, first it has been converted into binary form and then after store into Mysql database.

fetch_image($image_id) - This method has first fetch single user data based on value of primary key, and from that data first it has fetch image and then after converted into binary and return image as an output of this method.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Images;
use Illuminate\Support\Facades\Response;
use Image;

class StoreImageController extends Controller
{
    function index()
    {
     $data = Images::latest()->paginate(5);
     return view('store_image', compact('data'))
       ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    function insert_image(Request $request)
    {
     $request->validate([
      'user_name'  => 'required',
      'user_image' => 'required|image|max:2048'
     ]);

     $image_file = $request->user_image;

     $image = Image::make($image_file);

     Response::make($image->encode('jpeg'));

     $form_data = array(
      'user_name'  => $request->user_name,
      'user_image' => $image
     );

     Images::create($form_data);

     return redirect()->back()->with('success', 'Image store in database successfully');
    }

    function fetch_image($image_id)
    {
     $image = Images::findOrFail($image_id);

     $image_file = Image::make($image->user_image);

     $response = Response::make($image_file->encode('jpeg'));

     $response->header('Content-Type', 'image/jpeg');

     return $response;
    }
}



Create View Blade File


In Laravel framework for display html output on web page, here it has use blade file which has been store under resources/views folder. Here in this views file, we have done following things.
  • Write code for display form data validation error
  • Write code for display success message
  • Make HTML form for enter name and select profile image
  • Make HTML table for display dynamic data on web page

resources/views/store_image.blade.php

<html>
<head>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Insert Image into Mysql Database in Laravel 6</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
 <div class="container">    
  <br />
  <h3 align="center">Insert Image into Mysql Database in Laravel 6</h3>
    <br />
    @if($errors->any())
    <div class="alert alert-danger">
           <ul>
           @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
           @endforeach
           </ul>
        </div>
    @endif

    @if(session()->has('success'))
     <div class="alert alert-success">
     {{ session()->get('success') }}
     </div>
    @endif
    <br />

    <div class="panel panel-default">
         <div class="panel-heading">
             <h3 class="panel-title">User Form</h3>
         </div>
         <div class="panel-body">
         <br />
         <form method="post" action="{{ url('store_image/insert_image') }}"  enctype="multipart/form-data">
          @csrf
          <div class="form-group">
          <div class="row">
           <label class="col-md-4" align="right">Enter Name</label>
           <div class="col-md-8">
            <input type="text" name="user_name" class="form-control" />
           </div>
          </div>
         </div>
         <div class="form-group">
          <div class="row">
           <label class="col-md-4" align="right">Select Profile Image</label>
           <div class="col-md-8">
            <input type="file" name="user_image" />
           </div>
          </div>
         </div>
         <div class="form-group" align="center">
          <br />
          <br />
          <input type="submit" name="store_image" class="btn btn-primary" value="Save" />
         </div>
         </form>
      </div>
     </div>
     <div class="panel panel-default">
         <div class="panel-heading">
             <h3 class="panel-title">User Data</h3>
         </div>
         <div class="panel-body">
         <div class="table-responsive">
                <table class="table table-bordered table-striped">
                  <tr>
                     <th width="30%">Image</th>
                     <th width="70%">Name</th>
                  </tr>
                  @foreach($data as $row)
                  <tr>
                   <td>
                    <img src="store_image/fetch_image/{{ $row->id }}"  class="img-thumbnail" width="75" />
                   </td>
                   <td>{{ $row->user_name }}</td>
                  </tr>
                  @endforeach
              </table>
              {!! $data->links() !!}
             </div>
         </div>
     </div>
    </div>
 </body>
</html>



Set Route


Before run Laravel application, first we have to set the route of Laravel controller class method. For this we have to open routes/web.php file and set the route of controller method.


Route::get('store_image', 'StoreImageController@index');

Route::post('store_image/insert_image', 'StoreImageController@insert_image');

Route::get('store_image/fetch_image/{id}', 'StoreImageController@fetch_image');


Here we have set the route of all controller class method.

Run Laravel Application


If our code is ready, now we need to check in browser. For this we have to start laravel server, for this we have to go command prompt and run following command.


php artisan serve


This command will start Laravel server and give us base url of our Laravel application. For check above code we have to write following url in browser.


http://127.0.0.1:8000/store_image


So, this is complete step by step process for how to insert images into mysql database in Laravel 6 framework and how to fetch images from mysql table and display on web page in Laravel 6 application. If you want to get source code of this tutorial in zip, you can feel free to email us at webslesson@gmail.com, we will reply you with attach source code zip file.