Friday, 24 February 2017

PHP PDO Pagination

In this post we have make discussion on topic like how to create Pagination by using PHP PDO Modal. If we have large number of data in our Mysql Database then at that time we want to create pagination for that data. This Pure PHP PDO pagination in which we have not use Ajax JQuery in this post but We have use simple PHP PDO code for make pagination. We have make simple pagination by using PHP PDO in which we have create only previous page and next page button only. We have use Bootstrap for displaying previous and next page button link. If you are using PHP PDO for Web Development then you can use this code for making pagination in your project.






Source Code


index.php



<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "testing";

try 
{
 $connect = new PDO("mysql:host=$host;dbname=$database", $username, $password);
 $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $query = "SELECT count(post_id) as total FROM tbl_posts";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $total = $row["total"];
 }
 $per_page = 10;
 $pages = ceil($total/$per_page);
 $page = 1;
 if(isset($_GET["page"]))
 {
  $page = $_GET["page"];
  $page = trim($page);
  if($page < 1)
  {
   $page = 1;
  }
 }
 $start = $per_page * ($page - 1);
 $previous = $page - 1;
 $next = $page + 1;
 $statement = $connect->prepare("SELECT * FROM tbl_posts LIMIT $start, $per_page");
 $statement->execute();
 $result = $statement->fetchAll();
}
catch(PDOException $e) 
{
 print_r($e->getMessage());
}
$connect = null;
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | PHP PDO Pagination</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>
 </head>
 <body>
  <br /><br />
  <div class="container">
   <h2 align="center">PHP PDO Pagination</a></h2>
   <br />
   <div class="table-responsive">
    <div align="center">
     <ul class="pager">
    <?php
    if(count($result) > 0)
    {
     if($page <= 1)
     {
      echo '
      <li class="previous disabled"><a href="#">Previous</a></li>
      <li class="next"><a href="index.php?page='.$next.'">Next</a></li>
      ';
     }
     elseif($page >= $pages)
     {
      echo '
      <li class="previous"><a href="index.php?page='.$previous.'">Previous</a></li>
      <li class="next disabled"><a href="#">Next</a></li>
      ';
     }
     else
     {
      echo '
      <li class="previous"><a href="index.php?page='.$previous.'">Previous</a></li>
      <li class="next"><a href="index.php?page='.$next.'">Next</a></li>
      ';
     }
    }
    else
    {
     echo "<p>No Data found.</p>";
    }
    ?>
     </ul>
    </div>
    <?php
    if(count($result) > 0)
    {
     echo '
     <table class="table table-bordered table-stripped">
      <tr>
       <th>Post ID</th>
       <th>Post Title</th>
       <th>Author</th>
       <th>Description</th>
      </tr>
     ';
     foreach($result as $key => $value)
     {
      echo '
      <tr>
       <td>'.$value["post_id"].'</td>
       <td>'.$value["post_title"].'</td>
       <td>'.$value["post_author"].'</td>
       <td>'.$value["post_description"].'</td>
      </tr>
      ';
     }
     echo '
     </table>
     <p>Total Records - '.$total.'</p>
     ';
    }
    ?>
   </div>
  </div>
 </body>
</html>


Database



 -- phpMyAdmin SQL Dump
-- version 4.3.11
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Feb 24, 2017 at 11:23 AM
-- Server version: 5.6.24
-- PHP Version: 5.6.8

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_posts`
--

CREATE TABLE IF NOT EXISTS `tbl_posts` (
  `post_id` int(11) NOT NULL,
  `post_title` varchar(250) NOT NULL,
  `post_author` varchar(150) NOT NULL,
  `post_description` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=102 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_posts`
--

INSERT INTO `tbl_posts` (`post_id`, `post_title`, `post_author`, `post_description`) VALUES
(2, 'orci, consectetuer euismod est arcu ac orci.', 'Hasad Beach', 'Curabitur ut odio vel est tempor bibendum. Donec felis orci, adipiscing non, luctus sit amet, faucibus ut, nulla. Cras eu'),
(3, 'dignissim. Maecenas ornare egestas ligula. Nullam', 'Zorita Hobbs', 'non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra'),
(4, 'vestibulum. Mauris magna. Duis dignissim', 'Rinah Mendoza', 'sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis'),
(5, 'turpis vitae purus gravida sagittis. Duis gravida. Praesent', 'Ria Stokes', 'diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a,'),
(6, 'massa. Suspendisse eleifend. Cras sed leo.', 'Colette Mcmahon', 'sit amet diam eu dolor egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue.'),
(7, 'dignissim tempor arcu. Vestibulum ut eros non enim commodo', 'Leilani Randolph', 'ridiculus mus. Donec dignissim magna a tortor. Nunc commodo auctor velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus.'),
(8, 'nec tempus scelerisque, lorem ipsum sodales purus, in', 'Farrah Rowland', 'luctus ut, pellentesque eget, dictum placerat, augue. Sed molestie. Sed id risus quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris'),
(9, 'vestibulum nec, euismod in, dolor. Fusce feugiat.', 'Shafira Payne', 'Suspendisse aliquet, sem ut cursus luctus, ipsum leo elementum sem, vitae aliquam'),
(10, 'scelerisque, lorem ipsum sodales', 'Henry Lloyd', 'molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl'),
(11, 'Pellentesque ultricies dignissim lacus. Aliquam', 'Alana Pratt', 'Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat. Vivamus nisi. Mauris nulla. Integer'),
(12, 'gravida molestie arcu. Sed eu nibh', 'Thaddeus Bird', 'urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis'),
(13, 'cursus. Integer', 'Brandon Wade', 'quis, pede. Praesent eu dui. Cum sociis natoque penatibus et magnis dis parturient'),
(14, 'et, lacinia vitae, sodales at, velit. Pellentesque ultricies', 'Colin Romero', 'quis diam luctus lobortis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt'),
(15, 'nec', 'Jaime Huffman', 'sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula'),
(16, 'lorem, luctus ut,', 'Vivian Nichols', 'laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa.'),
(17, 'sed sem egestas blandit. Nam', 'Ferris Mcdowell', 'fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia'),
(18, 'Mauris vel turpis. Aliquam adipiscing', 'Chandler Waters', 'magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris. Suspendisse aliquet molestie tellus. Aenean egestas'),
(19, 'Duis dignissim', 'Francesca Clayton', 'Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt'),
(20, 'ut, sem. Nulla interdum. Curabitur', 'Colette Workman', 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet'),
(21, 'molestie in, tempus eu, ligula. Aenean euismod mauris', 'Macey Burks', 'Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci.'),
(22, 'enim. Mauris quis turpis vitae purus gravida', 'Velma Finch', 'mauris. Suspendisse aliquet molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis. Donec'),
(23, 'Proin sed', 'Emi Baxter', 'non, cursus non, egestas a, dui. Cras pellentesque. Sed dictum. Proin eget odio. Aliquam vulputate ullamcorper magna. Sed eu eros.'),
(24, 'posuere, enim nisl elementum purus, accumsan interdum libero dui', 'Althea Lucas', 'urna. Vivamus molestie dapibus ligula. Aliquam erat volutpat. Nulla dignissim. Maecenas ornare egestas ligula. Nullam feugiat placerat velit. Quisque varius. Nam porttitor scelerisque neque. Nullam nisl. Maecenas malesuada fringilla'),
(25, 'velit. Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices.', 'Ignatius Mcdonald', 'Donec tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac metus vitae velit egestas lacinia. Sed congue, elit sed consequat auctor, nunc'),
(26, 'Cum sociis natoque penatibus et magnis dis', 'Rudyard Hubbard', 'sem ut dolor dapibus gravida. Aliquam tincidunt, nunc ac mattis ornare, lectus ante dictum mi, ac mattis velit justo nec ante.'),
(27, 'ornare, elit elit', 'John Wilkins', 'feugiat tellus lorem eu metus. In lorem. Donec elementum, lorem ut aliquam iaculis,'),
(28, 'tellus eu augue porttitor interdum. Sed auctor odio', 'Ashton Mullen', 'amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in'),
(29, 'neque sed sem egestas blandit. Nam nulla', 'Ima Bernard', 'Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur'),
(30, 'Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing', 'Hedley Rose', 'Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy'),
(31, 'non, vestibulum nec, euismod in, dolor. Fusce feugiat.', 'Joelle Fox', 'orci tincidunt adipiscing. Mauris molestie pharetra nibh. Aliquam ornare, libero at auctor ullamcorper, nisl arcu'),
(32, 'mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate,', 'Beatrice Contreras', 'urna suscipit nonummy. Fusce fermentum fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus et'),
(33, 'Integer tincidunt aliquam arcu. Aliquam ultrices iaculis odio.', 'Driscoll Howard', 'consectetuer rhoncus. Nullam velit dui, semper et, lacinia vitae, sodales at, velit. Pellentesque ultricies dignissim lacus. Aliquam rutrum lorem ac'),
(34, 'scelerisque', 'Lance Schmidt', 'Phasellus vitae mauris sit amet lorem semper auctor. Mauris vel turpis. Aliquam'),
(35, 'Donec egestas.', 'Davis Callahan', 'eu tellus eu augue porttitor interdum. Sed auctor odio a purus. Duis elementum, dui quis accumsan'),
(36, 'Sed et libero. Proin mi. Aliquam', 'Xantha Emerson', 'placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante, iaculis nec, eleifend non, dapibus'),
(37, 'Vestibulum ut eros non enim', 'Zena Dodson', 'egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada vel, convallis in, cursus et, eros. Proin ultrices. Duis volutpat nunc sit amet metus.'),
(38, 'primis in faucibus orci luctus', 'Katelyn Booker', 'pretium aliquet, metus urna convallis erat, eget tincidunt dui augue eu tellus. Phasellus elit pede, malesuada vel, venenatis vel, faucibus id, libero. Donec consectetuer mauris id sapien. Cras dolor'),
(39, 'porttitor tellus non magna. Nam ligula elit, pretium et, rutrum', 'Tanya Galloway', 'Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer'),
(40, 'adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum.', 'Maris Rasmussen', 'non, bibendum sed, est. Nunc laoreet lectus quis massa. Mauris vestibulum, neque sed dictum eleifend, nunc risus varius orci, in consequat'),
(41, 'ac urna. Ut tincidunt vehicula risus. Nulla', 'Myra Pierce', 'neque tellus, imperdiet non, vestibulum nec, euismod in, dolor. Fusce feugiat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam auctor, velit eget laoreet posuere, enim'),
(42, 'a, magna. Lorem ipsum dolor sit', 'Hakeem Buck', 'elit erat vitae risus. Duis a mi fringilla mi lacinia mattis. Integer eu lacus. Quisque imperdiet, erat nonummy ultricies ornare, elit'),
(43, 'justo faucibus lectus, a sollicitudin orci sem eget massa.', 'Wilma Allen', 'a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis,'),
(44, 'ac mattis semper, dui lectus rutrum urna,', 'Serina Whitehead', 'vel nisl. Quisque fringilla euismod enim. Etiam gravida molestie arcu. Sed eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula. Nullam enim. Sed nulla ante,'),
(45, 'elit erat vitae risus. Duis a mi fringilla mi', 'Keane Owens', 'sodales elit erat vitae risus. Duis a mi fringilla mi lacinia mattis.'),
(46, 'dictum eleifend, nunc risus varius orci, in', 'Kevyn Mcguire', 'et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum'),
(47, 'nisl. Nulla eu neque pellentesque massa', 'Eve Tucker', 'per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt'),
(48, 'Duis volutpat nunc sit amet metus. Aliquam erat volutpat. Nulla', 'Jade Haney', 'torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi'),
(49, 'ac', 'Quynn Knowles', 'Curabitur vel lectus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor.'),
(50, 'Nunc ullamcorper, velit in aliquet', 'Marah Randolph', 'orci lacus vestibulum lorem, sit amet ultricies sem magna nec quam. Curabitur vel lectus. Cum sociis natoque penatibus'),
(51, 'ornare, lectus ante dictum mi, ac mattis velit', 'Eugenia Roth', 'Aliquam nisl. Nulla eu neque pellentesque massa lobortis ultrices. Vivamus rhoncus. Donec est. Nunc ullamcorper, velit in aliquet lobortis, nisi nibh lacinia orci, consectetuer'),
(52, 'at lacus. Quisque', 'Louis Castaneda', 'sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede, nonummy ut, molestie in, tempus eu, ligula. Aenean'),
(53, 'Vivamus euismod urna.', 'Edward Wells', 'tincidunt. Donec vitae erat vel pede blandit congue. In scelerisque scelerisque dui. Suspendisse ac'),
(54, 'odio.', 'Arden Golden', 'risus odio, auctor vitae, aliquet nec, imperdiet nec, leo. Morbi'),
(55, 'velit. Cras lorem lorem, luctus ut, pellentesque', 'Talon Freeman', 'ac risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam.'),
(56, 'mi.', 'Erich Rush', 'vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc'),
(57, 'vel arcu', 'Marah Gonzales', 'sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa.'),
(58, 'et tristique pellentesque, tellus sem mollis dui, in sodales elit', 'Nolan Shelton', 'eget varius ultrices, mauris ipsum porta elit, a feugiat tellus lorem eu metus. In lorem. Donec'),
(59, 'Mauris molestie pharetra nibh. Aliquam ornare, libero', 'Josephine Wyatt', 'orci luctus et ultrices posuere cubilia Curae; Phasellus ornare. Fusce mollis. Duis sit amet'),
(60, 'a feugiat tellus lorem eu metus. In', 'Jesse Hampton', 'accumsan laoreet ipsum. Curabitur consequat, lectus sit amet luctus vulputate, nisi sem semper erat, in consectetuer ipsum nunc id enim. Curabitur massa. Vestibulum accumsan'),
(61, 'eu lacus. Quisque imperdiet, erat nonummy ultricies', 'Wendy Dunlap', 'taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris ut quam'),
(62, 'penatibus et magnis dis parturient', 'Alexis Figueroa', 'semper egestas, urna justo faucibus lectus, a sollicitudin orci sem eget massa. Suspendisse eleifend. Cras sed leo. Cras vehicula aliquet libero. Integer in'),
(63, 'justo sit amet nulla. Donec non justo. Proin non massa', 'Stacey Goff', 'et magnis dis parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor.'),
(64, 'aliquam, enim nec tempus scelerisque,', 'Dara Nicholson', 'magna a neque. Nullam ut nisi a odio semper cursus. Integer'),
(65, 'nec ligula consectetuer rhoncus. Nullam velit dui, semper et, lacinia', 'Caesar Hess', 'leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum'),
(66, 'dictum. Proin eget odio. Aliquam vulputate ullamcorper', 'Ursa Swanson', 'a nunc. In at pede. Cras vulputate velit eu sem. Pellentesque ut ipsum ac mi eleifend egestas. Sed pharetra, felis eget varius ultrices, mauris'),
(67, 'non, feugiat nec, diam. Duis mi enim, condimentum eget,', 'Cooper Gould', 'Suspendisse dui. Fusce diam nunc, ullamcorper eu, euismod ac, fermentum vel, mauris. Integer sem elit, pharetra ut, pharetra sed, hendrerit a, arcu. Sed et libero. Proin mi.'),
(68, 'vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin', 'Destiny Boyle', 'ac turpis egestas. Fusce aliquet magna a neque. Nullam ut nisi a odio semper cursus. Integer mollis. Integer'),
(69, 'eleifend, nunc risus varius orci, in consequat enim diam', 'Clementine Saunders', 'consectetuer euismod est arcu ac orci. Ut semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis. In condimentum.'),
(70, 'Lorem', 'Gannon Dominguez', 'malesuada fames ac turpis egestas. Aliquam fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam nulla magna, malesuada'),
(71, 'at arcu. Vestibulum ante ipsum primis', 'Roary Ewing', 'nostra, per inceptos hymenaeos. Mauris ut quam vel sapien imperdiet ornare. In faucibus. Morbi vehicula. Pellentesque tincidunt tempus risus. Donec'),
(72, 'massa. Mauris vestibulum, neque', 'Suki Rich', 'consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque, tellus sem mollis dui, in'),
(73, 'amet massa. Quisque porttitor eros nec', 'Cameron Key', 'arcu et pede. Nunc sed orci lobortis augue scelerisque mollis. Phasellus libero mauris, aliquam eu, accumsan sed, facilisis vitae, orci. Phasellus dapibus quam quis diam. Pellentesque habitant morbi'),
(74, 'non', 'Teagan Caldwell', 'fringilla cursus purus. Nullam scelerisque neque sed sem egestas blandit. Nam'),
(75, 'vestibulum lorem, sit amet ultricies sem magna nec', 'Raven Clark', 'dictum eleifend, nunc risus varius orci, in consequat enim diam vel arcu. Curabitur ut odio vel'),
(76, 'nulla at sem molestie', 'Hoyt Ewing', 'id, ante. Nunc mauris sapien, cursus in, hendrerit consectetuer, cursus et, magna. Praesent interdum ligula eu enim. Etiam imperdiet dictum magna.'),
(77, 'hendrerit. Donec porttitor tellus non magna.', 'Declan Crawford', 'risus. Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique ac, eleifend vitae, erat.'),
(78, 'lorem lorem, luctus', 'Elliott Estrada', 'semper pretium neque. Morbi quis urna. Nunc quis arcu vel quam dignissim pharetra. Nam ac nulla. In tincidunt congue turpis.'),
(79, 'suscipit, est ac facilisis facilisis,', 'Quincy Morgan', 'egestas rhoncus. Proin nisl sem, consequat nec, mollis vitae, posuere at, velit. Cras lorem lorem, luctus ut, pellentesque eget, dictum placerat,'),
(80, 'ultrices. Duis volutpat nunc sit amet metus. Aliquam erat volutpat.', 'Carl Estes', 'Mauris blandit enim consequat purus. Maecenas libero est, congue a, aliquet vel, vulputate eu, odio. Phasellus at augue id ante dictum cursus.'),
(81, 'posuere vulputate, lacus. Cras interdum.', 'Neve Drake', 'erat nonummy ultricies ornare, elit elit fermentum risus, at fringilla purus mauris a nunc.'),
(82, 'quam.', 'Elvis Wyatt', 'iaculis odio. Nam interdum enim non nisi. Aenean eget metus. In nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus sit'),
(83, 'pede, ultrices a,', 'Quail Bradley', 'vitae dolor. Donec fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer'),
(84, 'auctor odio a purus. Duis elementum, dui', 'Lana Fitzgerald', 'cursus vestibulum. Mauris magna. Duis dignissim tempor arcu. Vestibulum ut'),
(85, 'Integer in magna. Phasellus dolor elit, pellentesque', 'Chantale Graves', 'fringilla. Donec feugiat metus sit amet ante. Vivamus non lorem'),
(86, 'et', 'Nevada Jones', 'fermentum arcu. Vestibulum ante ipsum primis in faucibus orci luctus'),
(87, 'neque', 'Rahim Herrera', 'Vestibulum accumsan neque et nunc. Quisque ornare tortor at risus. Nunc ac'),
(88, 'eu nibh vulputate mauris sagittis placerat. Cras dictum ultricies ligula.', 'Jennifer Barr', 'ante. Vivamus non lorem vitae odio sagittis semper. Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh. Donec est mauris,'),
(89, 'sodales nisi magna sed dui.', 'Shaine Gilmore', 'diam. Duis mi enim, condimentum eget, volutpat ornare, facilisis eget, ipsum. Donec sollicitudin adipiscing ligula. Aenean gravida nunc sed pede. Cum sociis natoque penatibus et magnis'),
(90, 'in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus', 'Sonya Barker', 'vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo. Vivamus nibh dolor, nonummy ac, feugiat non, lobortis quis, pede. Suspendisse dui. Fusce diam nunc, ullamcorper'),
(91, 'penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin', 'Martin Herring', 'dolor sit amet, consectetuer adipiscing elit. Etiam laoreet, libero et tristique pellentesque,'),
(92, 'felis, adipiscing fringilla, porttitor', 'Leo Coffey', 'vitae nibh. Donec est mauris, rhoncus id, mollis nec, cursus a, enim. Suspendisse aliquet, sem ut cursus'),
(93, 'est ac facilisis facilisis, magna tellus faucibus', 'Gavin Waller', 'convallis est, vitae sodales nisi magna sed dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales purus, in molestie tortor nibh sit amet orci. Ut sagittis lobortis mauris.'),
(94, 'nunc. Quisque ornare', 'Candice Maldonado', 'mauris eu elit. Nulla facilisi. Sed neque. Sed eget lacus. Mauris non dui nec'),
(95, 'malesuada. Integer id magna et ipsum cursus vestibulum. Mauris magna.', 'Yardley Lara', 'parturient montes, nascetur ridiculus mus. Donec dignissim magna a tortor.'),
(96, 'arcu. Curabitur ut odio vel est tempor bibendum. Donec felis', 'Cyrus Hodge', 'ac mattis velit justo nec ante. Maecenas mi felis, adipiscing fringilla, porttitor vulputate, posuere vulputate, lacus. Cras interdum. Nunc sollicitudin commodo ipsum. Suspendisse non leo.'),
(97, 'fermentum vel, mauris. Integer sem elit, pharetra', 'Hamilton Noble', 'Morbi metus. Vivamus euismod urna. Nullam lobortis quam a felis ullamcorper viverra. Maecenas iaculis aliquet diam. Sed diam lorem, auctor quis, tristique'),
(98, 'Duis risus odio, auctor vitae, aliquet nec, imperdiet', 'Adria Burnett', 'arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin'),
(99, 'cursus et, magna. Praesent interdum ligula', 'Wang Moon', 'semper auctor. Mauris vel turpis. Aliquam adipiscing lobortis risus. In mi pede,'),
(100, 'eget odio. Aliquam vulputate ullamcorper magna. Sed eu', 'Gavin Jacobs', 'Cras vehicula aliquet libero. Integer in magna. Phasellus dolor elit, pellentesque a, facilisis non, bibendum sed, est.'),
(101, 'tristique senectus', 'Ria Howard', 'ipsum non arcu. Vivamus sit amet risus. Donec egestas. Aliquam nec');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_posts`
--
ALTER TABLE `tbl_posts`
  ADD PRIMARY KEY (`post_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_posts`
--
ALTER TABLE `tbl_posts`
  MODIFY `post_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=102;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


Wednesday, 22 February 2017

Upload File without using Form Submit in Ajax PHP



In this post we have discuss one of the topic of based on ajax which is how to upload file or image without using Form Submit with Ajax request and PHP Script without page refresh.

For Upload Image, We have first select Image and when we have select image then Image will be uploaded to it's define location. Because we have use jquery change event on input type file element.

In this we have also perform some validation like allowed image type and size of selected image also. This all validation we will perform also done by jquery.

For sending selected image to server we have use FormData() object. By using FormData() object we have send selected Image for server by using Ajax request. So by using FormData() Object and Ajax we have send selected file to PHP script. By using PHP Script we can upload selected file or Image to server without refresh of page.

After done uploading selected Image we have also uploaded image on web page without refreshing of page. So this is our simple tutorial on How to Upload Image without using Form Submit in Ajax PHP.



Source Code


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Upload File without using Form Submit in Ajax PHP</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>
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:700px;">
   <h2 align="center">Upload File without using Form Submit in Ajax PHP</h2>
   <br />
   <label>Select Image</label>
   <input type="file" name="file" id="file" />
   <br />
   <span id="uploaded_image"></span>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $(document).on('change', '#file', function(){
  var name = document.getElementById("file").files[0].name;
  var form_data = new FormData();
  var ext = name.split('.').pop().toLowerCase();
  if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1) 
  {
   alert("Invalid Image File");
  }
  var oFReader = new FileReader();
  oFReader.readAsDataURL(document.getElementById("file").files[0]);
  var f = document.getElementById("file").files[0];
  var fsize = f.size||f.fileSize;
  if(fsize > 2000000)
  {
   alert("Image File Size is very big");
  }
  else
  {
   form_data.append("file", document.getElementById('file').files[0]);
   $.ajax({
    url:"upload.php",
    method:"POST",
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    beforeSend:function(){
     $('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
    },   
    success:function(data)
    {
     $('#uploaded_image').html(data);
    }
   });
  }
 });
});
</script>


upload.php



<?php
//upload.php
if($_FILES["file"]["name"] != '')
{
 $test = explode('.', $_FILES["file"]["name"]);
 $ext = end($test);
 $name = rand(100, 999) . '.' . $ext;
 $location = './upload/' . $name;  
 move_uploaded_file($_FILES["file"]["tmp_name"], $location);
 echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
}
?>

Friday, 10 February 2017

Live Search JSON Data Using Ajax jQuery



Hi, You have already know Ajax Live Data search by using Mysql table data in PHP, but in this post we have show you how to make live data search of JSON File data by using Ajax JQuery. We all already know JSON stand for Java Script Object Notation and it is a very lightweight data processing format and it can easy for human read. So In this post we have store data in JSON file and by using Ajax JQuery we will make simple Live data search application that search data from JSON file and display on web browser without refreshing of page.

In this example we have first create simple employee data like name, image and location of employee and store into JSON format in file and that file we have store in our working folder. After this we have create one simple page and in that page we have create one textbox. So when we have type something in textbox then at that time jquery event will file which search data from JSON file. For load JSON file data in our page we have use Ajax getJSON() method. By using this method we can load JSON file data in our page. After loading JSON File data we want search data from this JSON data, so we have use simple jquery regular expression. By using this jquery regular expression can search JSON data by key and value pair and for display search data on web page we have use Jquery append() method. This method will append html code in particular HTML tag and that display on web page. Here search data like employee image, name and location will load below textbox in drop down list format and here we can search by name and location also.

This type of feature is mostly we can see in Social media site like facebook etc. But we can also use this feature in our developing project also. In this post we have share you a source code and online demo also for better understanding regarding this feature like Live JSON data search by using Ajax JQuery.





Online Demo



JSON Live Data Search using Ajax JQuery

Employee Data








    Source Code


    
    <!DOCTYPE html>
    <html>
     <head>
      <title>Webslesson Tutorial | Search HTML Table Data by using JQuery</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>
      #result {
       position: absolute;
       width: 100%;
       max-width:870px;
       cursor: pointer;
       overflow-y: auto;
       max-height: 400px;
       box-sizing: border-box;
       z-index: 1001;
      }
      .link-class:hover{
       background-color:#f1f1f1;
      }
      </style>
     </head>
     <body>
      <br /><br />
      <div class="container" style="width:900px;">
       <h2 align="center">JSON Live Data Search using Ajax JQuery</h2>
       <h3 align="center">Employee Data</h3>   
       <br /><br />
       <div align="center">
        <input type="text" name="search" id="search" placeholder="Search Employee Details" class="form-control" />
       </div>
       <ul class="list-group" id="result"></ul>
       <br />
      </div>
     </body>
    </html>
    
    <script>
    $(document).ready(function(){
     $.ajaxSetup({ cache: false });
     $('#search').keyup(function(){
      $('#result').html('');
      $('#state').val('');
      var searchField = $('#search').val();
      var expression = new RegExp(searchField, "i");
      $.getJSON('data.json', function(data) {
       $.each(data, function(key, value){
        if (value.name.search(expression) != -1 || value.location.search(expression) != -1)
        {
         $('#result').append('<li class="list-group-item link-class"><img src="'+value.image+'" height="40" width="40" class="img-thumbnail" /> '+value.name+' | <span class="text-muted">'+value.location+'</span></li>');
        }
       });   
      });
     });
     
     $('#result').on('click', 'li', function() {
      var click_text = $(this).text().split('|');
      $('#search').val($.trim(click_text[0]));
      $("#result").html('');
     });
    });
    </script>
    
    

    data.json


    
    [
      {
        "name":"Angel Lewis",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/3/000/0d4/2f7/07a3d35.jpg",
        "location":"Seattle, WA"
      },
      {
        "name":"Justin Dean",
        "image": "https://media.licdn.com/mpr/mpr/shrink_100_100/AAEAAQAAAAAAAAIMAAAAJGExNTE4OWY4LWU4ODMtNDA2ZS1iNWI1LWNkYmIyOWMyMGQ5Zg.jpg",
        "location":"Muscatine, IA"
      },
      {
        "name":"Nora Blake",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/2/005/0b8/118/387e091.jpg",
        "location":"Seattle, WA"
      },
      {
        "name":"Russell Fox",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/2/000/084/26e/2d9e05b.jpg",
        "location":"Albuquerque, NM"
      },
      {
        "name":"Daryl Bradley",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/3/000/042/0ad/197566e.jpg",
        "location":"Buckeystown, MD"
      },
      {
        "name":"Benjamin Gonzales",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/8/005/0b2/1c9/2a423c1.jpg",
        "location":"Atlanta, GA"
      },
      {
        "name":"Viola Francis",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAASJAAAAJGMyMTUzN2EyLTExY2ItNDZiNS1hMTY1LTI4NDA2NDMwZmFkNg.jpg",
        "location":"Zanesville, OH"
      },
      {
        "name":"Reginald Benson",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/1/000/10f/3cc/275a407.jpg",
        "location":"Gilbert, AZ"
      },
      {
        "name":"Glenda Ray",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/8/005/0ac/1ca/07c25a2.jpg",
        "location":"Baltimore, MD"
      },
      {
        "name":"Paula Vargas",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/5/005/03e/073/36a5c47.jpg",
        "location":"Baltimore, MD"
      },
      {
        "name":"Mark Armstrong",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/5/005/010/09b/39b122d.jpg",
        "location":"Hallandale Beach, FL"
      },
      {
        "name":"Jaime Campbell",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAATUAAAAJDJkY2Q1Mzk0LTI1YzItNDFhNy04ZmQ0LWY3NzZlZTZlNGVmYw.jpg",
        "location":"Zanesville, OH"
      },
      {
        "name":"Mike Beck",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/2/000/01c/0d4/2b69e7c.jpg",
        "location":"Garner, NC"
      },
      {
        "name":"Ann Lowe",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/7/000/1f6/019/29cd853.jpg",
        "location":"Cabin John, MD"
      },
      {
        "name":"Ryan Wolfe",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/1/000/0bf/335/05a57f6.jpg",
        "location":"Los Angeles, CA"
      },
      {
        "name":"Dwayne Gutierrez",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/3/000/29b/028/2426536.jpg",
        "location":"San Jose, CA"
      },
      {
        "name":"Bill Burke",
        "image": "https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/7/000/1bc/12e/1423106.jpg",
        "location":"Bakersfield, CA"
      }
    ]
    
    

    Wednesday, 25 January 2017

    How to uncheck checked radio button by using Javascript


    This post is based on simple concept like how to unchecked checked radio button by using simple Javascript. Suppose you have developed simple HTML form and there is one data which are optional and we have use radio button for get that data by using radio button element. So someone has select any radio button option but after this we want to unchecked checked radio button but normally we can't unchecked radio button. This is because when we have check any radio button then after for unchecked we want to refresh whole page. So for this we have built this tutorial. In this post we have use simple Javascript for unchecked radio button. In this post we have share source code and online demo also.


    Online Demo


    Option 1


    Option 2


    Option 3


    Source Code


    
    <html>  
     <head>  
      <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
      <meta charset="utf-8">  
      <title>How to uncheck checked radio button by using Javascript</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">How to uncheck checked radio button by using Javascript</h3>
       <h3><input type="radio" name="radio_button" value="option 1" /> Option 1</h3><br />
       <h3><input type="radio" name="radio_button" value="option 2" /> Option 2</h3><br />
       <h3><input type="radio" name="radio_button" value="option 3" /> Option 3</h3><br />
      </div>  
     </body>  
    </html>
     
    <script type="text/javascript">
     var radio_button_list = document.getElementsByName('radio_button');
     var radio_button;
     var count;
     for(count = 0; count<radio_button_list.length; count++)
     {
      radio_button_list[count].onclick = function(){
       if(radio_button == this)
       {
        this.checked = false;
        radio_button = null;
       }
       else
       {
        radio_button = this;
       }
      };
     }
    
    </script>
    
    



    Saturday, 21 January 2017

    PHP PDO Ajax CRUD with Data Tables and Bootstrap Modals



    Hi, This is one more post on CRUD system in PHP. But in this tutorial We have made CRUD system by using Jquery Datatables plugin and Bootstrap Modals as front end tools and as back end script we have use PHP PDO Modal with Jquery and Ajax. In this post we have describe how to use Jquery Datatables plugin for Server-Side processing with PHP and Ajax. We have already made different CRUD Operation System in PHP. Here is some post in which we have already CRUD system by using PHP. You can also check demo online. We have also provide demo link with this post.




    We have already make CRUD Operation system in Codeigniter Framework also which you can find from above link. In this system User can Create or Insert new Data with Upload Image, Read or Fetch Data from table, Update or Edit data and Delete or Remove data. So in this System user can perform all CRUD Operation on single page without going to another page. So we can also called this Crud system to Single page CRUD System also.

    In our previous post we have already make CRUD system by using PHP PDO modal with Ajax JQuery. In that system for display data we have mainualy create table and display data in that table but in this system we have use Jquery Datatables plugin for displaying data on web page. In this system we have also add one more feature like user can also upload image with Inserting or updating of data. In this system we have use Ajax Jquery method with PHP PDO modal, So we can perform all CRUD Operation without refreshing of page and we can also upload image without refreshing of page also. For sending form data to server we have use Ajax FormData() Object, By using FormData() Object we have send form data to server via Ajax request.

    For making this system we have use JQuery Datatables plugin so we do want to write code for Searching table data, table column ordering, pagination and many more other features. JQuery Datatables plugin will automatically write code for this type of operation. We have use JQuery Datatables Server-Side Ajax processing for Insert Update Delete and Select of Data. Jquery Datatables plugin is light weight plugin for table grid system. So we have use this plugin in our system. I hope this tutorial will help you to learning this system. If you have any query please comment your query in comment box.



    Source Code


    index.php


        
    <html>
     <head>
      <title>Webslesson Demo - PHP PDO Ajax CRUD with Data Tables and Bootstrap Modals</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
      <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
      <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
      <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
      <style>
       body
       {
        margin:0;
        padding:0;
        background-color:#f1f1f1;
       }
       .box
       {
        width:1270px;
        padding:20px;
        background-color:#fff;
        border:1px solid #ccc;
        border-radius:5px;
        margin-top:25px;
       }
      </style>
     </head>
     <body>
      <div class="container box">
       <h1 align="center">PHP PDO Ajax CRUD with Data Tables and Bootstrap Modals</h1>
       <br />
       <div class="table-responsive">
        <br />
        <div align="right">
         <button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>
        </div>
        <br /><br />
        <table id="user_data" class="table table-bordered table-striped">
         <thead>
          <tr>
           <th width="10%">Image</th>
           <th width="35%">First Name</th>
           <th width="35%">Last Name</th>
           <th width="10%">Edit</th>
           <th width="10%">Delete</th>
          </tr>
         </thead>
        </table>
        
       </div>
      </div>
     </body>
    </html>
    
    <div id="userModal" class="modal fade">
     <div class="modal-dialog">
      <form method="post" id="user_form" enctype="multipart/form-data">
       <div class="modal-content">
        <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal">&times;</button>
         <h4 class="modal-title">Add User</h4>
        </div>
        <div class="modal-body">
         <label>Enter First Name</label>
         <input type="text" name="first_name" id="first_name" class="form-control" />
         <br />
         <label>Enter Last Name</label>
         <input type="text" name="last_name" id="last_name" class="form-control" />
         <br />
         <label>Select User Image</label>
         <input type="file" name="user_image" id="user_image" />
         <span id="user_uploaded_image"></span>
        </div>
        <div class="modal-footer">
         <input type="hidden" name="user_id" id="user_id" />
         <input type="hidden" name="operation" id="operation" />
         <input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
       </div>
      </form>
     </div>
    </div>
    
    <script type="text/javascript" language="javascript" >
    $(document).ready(function(){
     $('#add_button').click(function(){
      $('#user_form')[0].reset();
      $('.modal-title').text("Add User");
      $('#action').val("Add");
      $('#operation').val("Add");
      $('#user_uploaded_image').html('');
     });
     
     var dataTable = $('#user_data').DataTable({
      "processing":true,
      "serverSide":true,
      "order":[],
      "ajax":{
       url:"fetch.php",
       type:"POST"
      },
      "columnDefs":[
       {
        "targets":[0, 3, 4],
        "orderable":false,
       },
      ],
    
     });
    
     $(document).on('submit', '#user_form', function(event){
      event.preventDefault();
      var firstName = $('#first_name').val();
      var lastName = $('#last_name').val();
      var extension = $('#user_image').val().split('.').pop().toLowerCase();
      if(extension != '')
      {
       if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
       {
        alert("Invalid Image File");
        $('#user_image').val('');
        return false;
       }
      } 
      if(firstName != '' && lastName != '')
      {
       $.ajax({
        url:"insert.php",
        method:'POST',
        data:new FormData(this),
        contentType:false,
        processData:false,
        success:function(data)
        {
         alert(data);
         $('#user_form')[0].reset();
         $('#userModal').modal('hide');
         dataTable.ajax.reload();
        }
       });
      }
      else
      {
       alert("Both Fields are Required");
      }
     });
     
     $(document).on('click', '.update', function(){
      var user_id = $(this).attr("id");
      $.ajax({
       url:"fetch_single.php",
       method:"POST",
       data:{user_id:user_id},
       dataType:"json",
       success:function(data)
       {
        $('#userModal').modal('show');
        $('#first_name').val(data.first_name);
        $('#last_name').val(data.last_name);
        $('.modal-title').text("Edit User");
        $('#user_id').val(user_id);
        $('#user_uploaded_image').html(data.user_image);
        $('#action').val("Edit");
        $('#operation').val("Edit");
       }
      })
     });
     
     $(document).on('click', '.delete', function(){
      var user_id = $(this).attr("id");
      if(confirm("Are you sure you want to delete this?"))
      {
       $.ajax({
        url:"delete.php",
        method:"POST",
        data:{user_id:user_id},
        success:function(data)
        {
         alert(data);
         dataTable.ajax.reload();
        }
       });
      }
      else
      {
       return false; 
      }
     });
     
     
    });
    </script>
       

    db.php


        
    <?php
    
    $username = 'root';
    $password = '';
    $connection = new PDO( 'mysql:host=localhost;dbname=crud', $username, $password );
    
    ?>
       

    function.php


        
    <?php
    
    function upload_image()
    {
     if(isset($_FILES["user_image"]))
     {
      $extension = explode('.', $_FILES['user_image']['name']);
      $new_name = rand() . '.' . $extension[1];
      $destination = './upload/' . $new_name;
      move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
      return $new_name;
     }
    }
    
    function get_image_name($user_id)
    {
     include('db.php');
     $statement = $connection->prepare("SELECT image FROM users WHERE id = '$user_id'");
     $statement->execute();
     $result = $statement->fetchAll();
     foreach($result as $row)
     {
      return $row["image"];
     }
    }
    
    function get_total_all_records()
    {
     include('db.php');
     $statement = $connection->prepare("SELECT * FROM users");
     $statement->execute();
     $result = $statement->fetchAll();
     return $statement->rowCount();
    }
    
    ?>
       

    fetch.php


        
    <?php
    include('db.php');
    include('function.php');
    $query = '';
    $output = array();
    $query .= "SELECT * FROM users ";
    if(isset($_POST["search"]["value"]))
    {
     $query .= 'WHERE first_name LIKE "%'.$_POST["search"]["value"].'%" ';
     $query .= 'OR last_name LIKE "%'.$_POST["search"]["value"].'%" ';
    }
    if(isset($_POST["order"]))
    {
     $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
    }
    else
    {
     $query .= 'ORDER BY id DESC ';
    }
    if($_POST["length"] != -1)
    {
     $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
    }
    $statement = $connection->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    $data = array();
    $filtered_rows = $statement->rowCount();
    foreach($result as $row)
    {
     $image = '';
     if($row["image"] != '')
     {
      $image = '<img src="upload/'.$row["image"].'" class="img-thumbnail" width="50" height="35" />';
     }
     else
     {
      $image = '';
     }
     $sub_array = array();
     $sub_array[] = $image;
     $sub_array[] = $row["first_name"];
     $sub_array[] = $row["last_name"];
     $sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>';
     $sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button>';
     $data[] = $sub_array;
    }
    $output = array(
     "draw"    => intval($_POST["draw"]),
     "recordsTotal"  =>  $filtered_rows,
     "recordsFiltered" => get_total_all_records(),
     "data"    => $data
    );
    echo json_encode($output);
    ?>
       

    insert.php


        
    <?php
    include('db.php');
    include('function.php');
    if(isset($_POST["operation"]))
    {
     if($_POST["operation"] == "Add")
     {
      $image = '';
      if($_FILES["user_image"]["name"] != '')
      {
       $image = upload_image();
      }
      $statement = $connection->prepare("
       INSERT INTO users (first_name, last_name, image) 
       VALUES (:first_name, :last_name, :image)
      ");
      $result = $statement->execute(
       array(
        ':first_name' => $_POST["first_name"],
        ':last_name' => $_POST["last_name"],
        ':image'  => $image
       )
      );
      if(!empty($result))
      {
       echo 'Data Inserted';
      }
     }
     if($_POST["operation"] == "Edit")
     {
      $image = '';
      if($_FILES["user_image"]["name"] != '')
      {
       $image = upload_image();
      }
      else
      {
       $image = $_POST["hidden_user_image"];
      }
      $statement = $connection->prepare(
       "UPDATE users 
       SET first_name = :first_name, last_name = :last_name, image = :image  
       WHERE id = :id
       "
      );
      $result = $statement->execute(
       array(
        ':first_name' => $_POST["first_name"],
        ':last_name' => $_POST["last_name"],
        ':image'  => $image,
        ':id'   => $_POST["user_id"]
       )
      );
      if(!empty($result))
      {
       echo 'Data Updated';
      }
     }
    }
    
    ?>
       

    fetch_single.php


        
    <?php
    include('db.php');
    include('function.php');
    if(isset($_POST["user_id"]))
    {
     $output = array();
     $statement = $connection->prepare(
      "SELECT * FROM users 
      WHERE id = '".$_POST["user_id"]."' 
      LIMIT 1"
     );
     $statement->execute();
     $result = $statement->fetchAll();
     foreach($result as $row)
     {
      $output["first_name"] = $row["first_name"];
      $output["last_name"] = $row["last_name"];
      if($row["image"] != '')
      {
       $output['user_image'] = '<img src="upload/'.$row["image"].'" class="img-thumbnail" width="50" height="35" /><input type="hidden" name="hidden_user_image" value="'.$row["image"].'" />';
      }
      else
      {
       $output['user_image'] = '<input type="hidden" name="hidden_user_image" value="" />';
      }
     }
     echo json_encode($output);
    }
    ?>
       

    delete.php


        
    <?php
    
    include('db.php');
    include("function.php");
    
    if(isset($_POST["user_id"]))
    {
     $image = get_image_name($_POST["user_id"]);
     if($image != '')
     {
      unlink("upload/" . $image);
     }
     $statement = $connection->prepare(
      "DELETE FROM users WHERE id = :id"
     );
     $result = $statement->execute(
      array(
       ':id' => $_POST["user_id"]
      )
     );
     
     if(!empty($result))
     {
      echo 'Data Deleted';
     }
    }
    
    
    
    ?>
       

    Database


        
    --
    -- Database: `crud`
    --
    
    -- --------------------------------------------------------
    
    --
    -- Table structure for table `users`
    --
    
    CREATE TABLE IF NOT EXISTS `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `first_name` varchar(150) NOT NULL,
      `last_name` varchar(150) NOT NULL,
      `image` varchar(150) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=74 ;
    
    --
    -- Dumping data for table `users`
    --
    
    INSERT INTO `users` (`id`, `first_name`, `last_name`, `image`) VALUES
    (18, 'Joseph', 'Harman', '1.jpg'),
    (19, 'John', 'Moss', '4.jpg'),
    (20, 'Lillie', 'Ferrarium', '3.jpg'),
    (21, 'Yolanda', 'Green', '5.jpg'),
    (22, 'Cara', 'Gariepy', '7.jpg'),
    (23, 'Christine', 'Johnson', '11.jpg'),
    (24, 'Alana', 'Decruze', '12.jpg'),
    (25, 'Krista', 'Correa', '13.jpg'),
    (26, 'Charles', 'Martin', '14.jpg'),
    (70, 'Cindy', 'Canady', '18211.jpg'),
    (73, 'Daphne', 'Frost', '8288.jpg'),
    (69, 'Frank', 'Lemons', '22610.jpg'),
    (66, 'Margaret', 'Ault', '14365.jpg'),
    (71, 'Christina', 'Wilke', '9248.jpg'),
    (68, 'Roy', 'Newton', '27282.jpg');
       





    Saturday, 7 January 2017

    PHP PDO CRUD with Ajax Jquery and Bootstrap



    This is one more post on How to create Crud system in PHP Language. But in this post we have make Crud System in PHP by using PHP PDO Modal class with Ajax Jquery with Bootstrap. In this system we have use Ajax JQuery method with PHP PDO modal, so we can perform all CRUD operation like Create, Read, Update and Delete on single page event without refresh of page.

    We have already make this type of Crud system by using Simple PHP Object Oriented Programming and we have also make Crud system in Codeigniter Framework also. But now we have use PHP PDO Modal class for making this Crud system in PHP. There are many benefits of using PHP PDO for our web development projects. Following are the benefits of using PHP PDO.

    • It is an Object Oriented.
    • Bind parameters in statements.
    • Allows for prepared statements and rollback functionality
    • Throws catch able exceptions for better error handling.. and many more
    If you have use PHP PDO in your project, then you can use different databases with same code, you have not re-write new code for different database engine. You can use same code for your system operation like Insert, Update, Delete and Fetch data from database in PHP.

    In this tutorial you can find how to Insert or Add data, Update or Edit Data, Delete or remove data and Select or Fetch data from database by using PHP PDO with Ajax JQuery. You can find Source source code for how to perform this crud operation in PHP PDO with JQuery Ajax method. By using this source code you can make single page CRUD application by using PHP PDO with Ajax JQuery.



    Source Code


    index.php


     
      <html>
     <head>
      <title>How to Read Mysql Data by using PHP PDO with Ajax - PHP PDO CRUD with Ajax</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
      <style>
       body
       {
        margin:0;
        padding:0;
        background-color:#f1f1f1;
       }
       .box
       {
        width:1270px;
        padding:20px;
        background-color:#fff;
        border:1px solid #ccc;
        border-radius:5px;
        margin-top:100px;
       }
      </style>
     </head>
     <body>
      <div class="container box">
       <h1 align="center">PHP PDO CRUD with Ajax Jquery and Bootstrap</h1>
       <br />
       <div align="right">
        <button type="button" id="modal_button" class="btn btn-info">Create Records</button>
        <!-- It will show Modal for Create new Records !-->
       </div>
       <br />
       <div id="result" class="table-responsive"> <!-- Data will load under this tag!-->
    
       </div>
      </div>
     </body>
    </html>
    
    <!-- This is Customer Modal. It will be use for Create new Records and Update Existing Records!-->
    <div id="customerModal" class="modal fade">
     <div class="modal-dialog">
      <div class="modal-content">
       <div class="modal-header">
        <h4 class="modal-title">Create New Records</h4>
       </div>
       <div class="modal-body">
        <label>Enter First Name</label>
        <input type="text" name="first_name" id="first_name" class="form-control" />
        <br />
        <label>Enter Last Name</label>
        <input type="text" name="last_name" id="last_name" class="form-control" />
        <br />
       </div>
       <div class="modal-footer">
        <input type="hidden" name="customer_id" id="customer_id" />
        <input type="submit" name="action" id="action" class="btn btn-success" />
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
       </div>
      </div>
     </div>
    </div>
    
    <script>
    $(document).ready(function(){
     fetchUser(); //This function will load all data on web page when page load
     function fetchUser() // This function will fetch data from table and display under <div id="result">
     {
      var action = "Load";
      $.ajax({
       url : "action.php", //Request send to "action.php page"
       method:"POST", //Using of Post method for send data
       data:{action:action}, //action variable data has been send to server
       success:function(data){
        $('#result').html(data); //It will display data under div tag with id result
       }
      });
     }
    
     //This JQuery code will Reset value of Modal item when modal will load for create new records
     $('#modal_button').click(function(){
      $('#customerModal').modal('show'); //It will load modal on web page
      $('#first_name').val(''); //This will clear Modal first name textbox
      $('#last_name').val(''); //This will clear Modal last name textbox
      $('.modal-title').text("Create New Records"); //It will change Modal title to Create new Records
      $('#action').val('Create'); //This will reset Button value ot Create
     });
    
     //This JQuery code is for Click on Modal action button for Create new records or Update existing records. This code will use for both Create and Update of data through modal
     $('#action').click(function(){
      var firstName = $('#first_name').val(); //Get the value of first name textbox.
      var lastName = $('#last_name').val(); //Get the value of last name textbox
      var id = $('#customer_id').val();  //Get the value of hidden field customer id
      var action = $('#action').val();  //Get the value of Modal Action button and stored into action variable
      if(firstName != '' && lastName != '') //This condition will check both variable has some value
      {
       $.ajax({
        url : "action.php",    //Request send to "action.php page"
        method:"POST",     //Using of Post method for send data
        data:{firstName:firstName, lastName:lastName, id:id, action:action}, //Send data to server
        success:function(data){
         alert(data);    //It will pop up which data it was received from server side
         $('#customerModal').modal('hide'); //It will hide Customer Modal from webpage.
         fetchUser();    // Fetch User function has been called and it will load data under divison tag with id result
        }
       });
      }
      else
      {
       alert("Both Fields are Required"); //If both or any one of the variable has no value them it will display this message
      }
     });
    
     //This JQuery code is for Update customer data. If we have click on any customer row update button then this code will execute
     $(document).on('click', '.update', function(){
      var id = $(this).attr("id"); //This code will fetch any customer id from attribute id with help of attr() JQuery method
      var action = "Select";   //We have define action variable value is equal to select
      $.ajax({
       url:"action.php",   //Request send to "action.php page"
       method:"POST",    //Using of Post method for send data
       data:{id:id, action:action},//Send data to server
       dataType:"json",   //Here we have define json data type, so server will send data in json format.
       success:function(data){
        $('#customerModal').modal('show');   //It will display modal on webpage
        $('.modal-title').text("Update Records"); //This code will change this class text to Update records
        $('#action').val("Update");     //This code will change Button value to Update
        $('#customer_id').val(id);     //It will define value of id variable to this customer id hidden field
        $('#first_name').val(data.first_name);  //It will assign value to modal first name texbox
        $('#last_name').val(data.last_name);  //It will assign value of modal last name textbox
       }
      });
     });
    
     //This JQuery code is for Delete customer data. If we have click on any customer row delete button then this code will execute
     $(document).on('click', '.delete', function(){
      var id = $(this).attr("id"); //This code will fetch any customer id from attribute id with help of attr() JQuery method
      if(confirm("Are you sure you want to remove this data?")) //Confim Box if OK then
      {
       var action = "Delete"; //Define action variable value Delete
       $.ajax({
        url:"action.php",    //Request send to "action.php page"
        method:"POST",     //Using of Post method for send data
        data:{id:id, action:action}, //Data send to server from ajax method
        success:function(data)
        {
         fetchUser();    // fetchUser() function has been called and it will load data under divison tag with id result
         alert(data);    //It will pop up which data it was received from server side
        }
       })
      }
      else  //Confim Box if cancel then 
      {
       return false; //No action will perform
      }
     });
    });
    </script>
     
    

    action.php


     
      <?php
    //Database connection by using PHP PDO
    $username = 'root';
    $password = '';
    $connection = new PDO( 'mysql:host=localhost;dbname=crud', $username, $password ); // Create Object of PDO class by connecting to Mysql database
    
    if(isset($_POST["action"])) //Check value of $_POST["action"] variable value is set to not
    {
     //For Load All Data
     if($_POST["action"] == "Load") 
     {
      $statement = $connection->prepare("SELECT * FROM customers ORDER BY id DESC");
      $statement->execute();
      $result = $statement->fetchAll();
      $output = '';
      $output .= '
       <table class="table table-bordered">
        <tr>
         <th width="40%">First Name</th>
         <th width="40%">Last Name</th>
         <th width="10%">Update</th>
         <th width="10%">Delete</th>
        </tr>
      ';
      if($statement->rowCount() > 0)
      {
       foreach($result as $row)
       {
        $output .= '
        <tr>
         <td>'.$row["first_name"].'</td>
         <td>'.$row["last_name"].'</td>
         <td><button type="button" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button></td>
         <td><button type="button" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button></td>
        </tr>
        ';
       }
      }
      else
      {
       $output .= '
        <tr>
         <td align="center">Data not Found</td>
        </tr>
       ';
      }
      $output .= '</table>';
      echo $output;
     }
    
     //This code for Create new Records
     if($_POST["action"] == "Create")
     {
      $statement = $connection->prepare("
       INSERT INTO customers (first_name, last_name) 
       VALUES (:first_name, :last_name)
      ");
      $result = $statement->execute(
       array(
        ':first_name' => $_POST["firstName"],
        ':last_name' => $_POST["lastName"]
       )
      );
      if(!empty($result))
      {
       echo 'Data Inserted';
      }
     }
    
     //This Code is for fetch single customer data for display on Modal
     if($_POST["action"] == "Select")
     {
      $output = array();
      $statement = $connection->prepare(
       "SELECT * FROM customers 
       WHERE id = '".$_POST["id"]."' 
       LIMIT 1"
      );
      $statement->execute();
      $result = $statement->fetchAll();
      foreach($result as $row)
      {
       $output["first_name"] = $row["first_name"];
       $output["last_name"] = $row["last_name"];
      }
      echo json_encode($output);
     }
    
     if($_POST["action"] == "Update")
     {
      $statement = $connection->prepare(
       "UPDATE customers 
       SET first_name = :first_name, last_name = :last_name 
       WHERE id = :id
       "
      );
      $result = $statement->execute(
       array(
        ':first_name' => $_POST["firstName"],
        ':last_name' => $_POST["lastName"],
        ':id'   => $_POST["id"]
       )
      );
      if(!empty($result))
      {
       echo 'Data Updated';
      }
     }
    
     if($_POST["action"] == "Delete")
     {
      $statement = $connection->prepare(
       "DELETE FROM customers WHERE id = :id"
      );
      $result = $statement->execute(
       array(
        ':id' => $_POST["id"]
       )
      );
      if(!empty($result))
      {
       echo 'Data Deleted';
      }
     }
    
    }
    
    ?>
     
    

    Database


     
     --
    -- Database: `crud`
    --
    
    -- --------------------------------------------------------
    
    --
    -- Table structure for table `customers`
    --
    
    CREATE TABLE IF NOT EXISTS `customers` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `first_name` varchar(255) NOT NULL,
      `last_name` varchar(255) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=68 ;
    
    --
    -- Dumping data for table `customers`
    --
    
    INSERT INTO `customers` (`id`, `first_name`, `last_name`) VALUES
    (18, 'Joseph', 'Harman'),
    (19, 'John', 'Moss'),
    (20, 'Lillie', 'Ferrarium'),
    (21, 'Yolanda', 'Green'),
    (22, 'Cara', 'Gariepy'),
    (55, 'Opal', 'Goree'),
    (23, 'Christine', 'Johnson'),
    (24, 'Alana', 'Decruze'),
    (25, 'Krista', 'Correa'),
    (26, 'Charles', 'Martin'),
    (54, 'Rhonda', 'Ocampo'),
    (51, 'Cecilia', 'Roy'),
    (52, 'Otto', 'Estes'),
    (53, 'Richardson', 'Fishback'),
    (56, 'Rudy', 'Buckley');
     
    

    Thursday, 29 December 2016

    PHP Mysql Ajax Crud using OOPS - Pagination


    In the web project, pagination is the most essential element in which we can displayed large number of data from Mysql database to on webpage. Then in that time Pagination make by Ajax is a very Ajax pagination is a excellent idea because it will assist to increase visibility of your website User Interface. This tutorial will help you about how can you create the Ajax pagination in PHP Object Oriented programming Script using jQuery and MySQL. Here We have made the very simple but very powerful code to developed pagination with jQuery, Ajax, PHP, and MySQL.

    By using Object Oriented PHP Script, We have first load data from the MySQL database with the Ajax pagination links. By Click on this Ajax pagination links, you can fetch the database table records except the records which you want to displayed. jQuery and Ajax will assist to fetch the data from the mysql database based on pagination links without refreshing of the page.

    First We have make changes in load_data() function, in this function we have add first one argument like page.

    function load_data(page)
    

    After this in that function we have add that page argument data has been passed in Ajax data option to send the value of this page variable to action.php page.

    data:{action:action, page:page},
    

    Write JQuery code on click on pagination links. Here .pagination_link is the class name of Ajax Pagination Link. When click on pagination link this code will execute and it will fetch value from id attribute of particular pagination link. In an id attribute we have store page number. After fetching page number we have called load_data(page) function and in that function we have pass value of page variable and that function load data for that page.

                  $(document).on('click', '.pagination_link', function(){
       var page = $(this).attr("id");
       load_data(page);
      });
    

    This code write on action.php page under load data if condition. Here first $record_per_page = 5; That means we have set display five records on web page. Then after we have define $page variable. In this variable store the value of $_POST["page"] variable which is comes from ajax method. If it not received $_POST["page] variable then we have set $page variable value to 1.

                    $record_per_page = 5;
      $page = '';
    
      if(isset($_POST["page"]))
      {
       $page = $_POST["page"];
      }
      else
      {
       $page = 1;
      }
    

    After this we have calculate from where we have start fetching data from database.

    $start_from = ($page - 1) * $record_per_page;
    

    After this we have called get_data_in_table() function which we have made under crud class, this function will execute query and display result in table format

    echo $object->get_data_in_table("SELECT * FROM users ORDER BY id DESC LIMIT $start_from, $record_per_page");
    

    Make one function with name like make_pagination_link() in crud class, this function has generate pagination link and send pagination link.

            function make_pagination_link($query, $record_per_page)
     {
      $output = '';
      $result = $this->execute_query($query);
      $total_records = mysqli_num_rows($result);
      $total_pages = ceil($total_records/$record_per_page);
      for($i=1; $i<=$total_pages; $i++)
      {
       $output .= '<span class="pagination_link" style="cursor:pointer; padding:6px; border:1px solid #ccc;" id="'.$i.'">'.$i.'</span>';
      }
      return $output;
     }
    

    Again go to action.php and called make_pagination_link() which return pagination link html format and which we have send to index page.

    echo $object->make_pagination_link("SELECT * FROM users ORDER by id", $record_per_page);
    

    Conclusion

    So Pagination is the last part of our Crud system which is developed by Object Oriented PHP programming with Ajax JQuery method. Lastly Pagination is a very important features of any website, specially if you have many large number of data stored into your database and at that time you want to group that data into different part and display in different pages then at that time Ajax Pagination is done best job like, you can access different pages of data without going to next page but stay on single page. So it is very import for any web application.





    Source Code of Whole System with Insert, Update Delete, Searching and Pagination


    crud.php


    <?php
    class Crud
    {
     //crud class
     public $connect;
     private $host = "localhost";
     private $username = 'root';
     private $password = '';
     private $database = 'crud';
    
     function __construct()
     {
      $this->database_connect();
     }
    
     public function database_connect()
     {
      $this->connect = mysqli_connect($this->host, $this->username, $this->password, $this->database);
     }
    
     public function execute_query($query)
     {
      return mysqli_query($this->connect, $query);
     }
    
     public function get_data_in_table($query)
     {
      $output = '';
      $result = $this->execute_query($query);
      $output .= '
      <table class="table table-bordered table-striped">
       <tr>
        <th width="10%">Image</th>
        <th width="35%">First Name</th>
        <th width="35%">Last Name</th>
        <th width="10%">Update</th>
        <th width="10%">Delete</th>
       </tr>
      ';
      if(mysqli_num_rows($result) > 0)
      {
       while($row = mysqli_fetch_object($result))
       {
        $output .= '
        <tr>
         <td><img src="upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" /></td>
         <td>'.$row->first_name.'</td>
         <td>'.$row->last_name.'</td>
         <td><button type="button" name="update" id="'.$row->id.'" class="btn btn-success btn-xs update">Update</button></td>
         <td><button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs delete">Delete</button></td>
        </tr>
        ';
       }
      }
      else
      {
       $output .= '
        <tr>
         <td colspan="5" align="center">No Data Found</td>
        </tr>
       ';
      }
      $output .= '</table>';
      return $output;
     } 
     function upload_file($file)
     {
      if(isset($file))
      {
       $extension = explode('.', $file["name"]);
       $new_name = rand() . '.' . $extension[1];
       $destination = './upload/' . $new_name;
       move_uploaded_file($file['tmp_name'], $destination);
       return $new_name;
      }
     }
    
     function make_pagination_link($query, $record_per_page)
     {
      $output = '';
      $result = $this->execute_query($query);
      $total_records = mysqli_num_rows($result);
      $total_pages = ceil($total_records/$record_per_page);
      for($i=1; $i<=$total_pages; $i++)
      {
       $output .= '<span class="pagination_link" style="cursor:pointer; padding:6px; border:1px solid #ccc;" id="'.$i.'">'.$i.'</span>';
      }
      return $output;
     }
    }
    ?>
    

    index.php


    <?php
    //index.php
    include 'crud.php';
    $object = new Crud();
    ?>
    <html>
     <head>
      <title>PHP Mysql Ajax Crud using OOPS - Pagination</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
      <style>
       body
       {
        margin:0;
        padding:0;
        background-color:#f1f1f1;
       }
       .box
       {
        width:1270px;
        padding:20px;
        background-color:#fff;
        border:1px solid #ccc;
        border-radius:5px;
        margin-top:10px;
       }
      </style>
     </head>
     <body>
      <div class="container box">
       <h3 align="center">PHP Mysql Ajax Crud using OOPS - Pagination</h3><br /><br />
       <div class="col-md-8">
        <button type="button" name="add" id="add" class="btn btn-success" data-toggle="collapse" data-target="#user_collapse">Add</button>
       </div>
       <div class="col-md-4">
        <input type="text" name="search" id="search" placeholder="Search" class="form-control" />
       </div>
       <br />
       <br />
       <div id="user_collapse" class="collapse">
        <form method="post" id="user_form">
         <label>Enter First Name</label>
         <input type="text" name="first_name" id="first_name" class="form-control" />
         <br />
         <label>Enter Last Name</label>
         <input type="text" name="last_name" id="last_name" class="form-control" />
         <br />
         <label>Select User Image</label>
         <input type="file" name="user_image" id="user_image" />
         <input type="hidden" name="hidden_user_image" id="hidden_user_image" />
         <span id="uploaded_image"></span>
         <br />
         <div align="center">
          <input type="hidden" name="action" id="action" />
          <input type="hidden" name="user_id" id="user_id" />
          <input type="submit" name="button_action" id="button_action" class="btn btn-default" value="Insert" />
         </div>
        </form>
       </div>
       <br /><br />
       <div id="user_table" class="table-responsive">
       </div>
      </div>
     </body>
    </html>
    
    <script type="text/javascript">
     $(document).ready(function(){
    
      load_data();
    
      $('#action').val("Insert");
    
      $('#add').click(function(){
       $('#user_form')[0].reset();
       $('#uploaded_image').html('');
       $('#button_action').val("Insert");
      });
      function load_data(page)
      {
       var action = "Load";
       $.ajax({
        url:"action.php",
        method:"POST",
        data:{action:action, page:page},
        success:function(data)
        {
         $('#user_table').html(data);
        }
       });
      }
    
      $(document).on('click', '.pagination_link', function(){
       var page = $(this).attr("id");
       load_data(page);
      });
    
      $('#user_form').on('submit', function(event){
       event.preventDefault();
       var firstName = $('#first_name').val();
       var lastName = $('#last_name').val();
       var extension = $('#user_image').val().split('.').pop().toLowerCase();
       if(extension != '')
       {
        if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
        {
         alert("Invalid Image File");
         $('#user_image').val('');
         return false;
        }
       }
       if(firstName != '' && lastName != '')
       {
        $.ajax({
         url:"action.php",
         method:"POST",
         data:new FormData(this),
         contentType:false,
         processData:false,
         success:function(data)
         {
          alert(data);
          $('#user_form')[0].reset();
          load_data();      
          $('#action').val("Insert");
          $('#button_action').val("Insert");
          $('#uploaded_image').html('');
         }
        })
       }
       else
       {
        alert("Both Fields are Required");
       }
      });
    
      $(document).on('click', '.update', function(){
       var user_id = $(this).attr("id");
       var action = "Fetch Single Data";
       $.ajax({
        url:"action.php",
        method:"POST",
        data:{user_id:user_id, action:action},
        dataType:"json",
        success:function(data)
        {
         $('.collapse').collapse("show");
         $('#first_name').val(data.first_name);
         $('#last_name').val(data.last_name);
         $('#uploaded_image').html(data.image);
         $('#hidden_user_image').val(data.user_image);
         $('#button_action').val("Edit");
         $('#action').val("Edit");
         $('#user_id').val(user_id);
        }
       });
      });
      
      $(document).on('click', '.delete', function(){
       var user_id = $(this).attr("id");
       var action = "Delete";
       if(confirm("Are you sure you want to delete this?"))
       {
        $.ajax({
         url:"action.php",
         method:"POST",
         data:{user_id:user_id, action:action},
         success:function(data)
         {
          alert(data);
          load_data();
         }
        });
       }
       else
       {
        return false;
       }
      });
      
      $('#search').keyup(function(){
       var query = $('#search').val();
       var action = "Search";
       if(query != '')
       {
        $.ajax({
         url:"action.php",
         method:"POST",
         data:{query:query, action:action},
         success:function(data)
         {
          $('#user_table').html(data);
         }
        });
       }
       else
       {
        load_data();
       }
      });
      
     });
    </script>
    

    action.php


    <?php
    //action.php
    include 'crud.php';
    $object = new Crud();
    if(isset($_POST["action"]))
    {
     if($_POST["action"] == "Load")
     {
      $record_per_page = 5;
      $page = '';
    
      if(isset($_POST["page"]))
      {
       $page = $_POST["page"];
      }
      else
      {
       $page = 1;
      }
      $start_from = ($page - 1) * $record_per_page;
    
      echo $object->get_data_in_table("SELECT * FROM users ORDER BY id DESC LIMIT $start_from, $record_per_page");
      echo '<br /><div align="center">';
      echo $object->make_pagination_link("SELECT * FROM users ORDER by id", $record_per_page);
      echo '</div><br />';
    
     }
     if($_POST["action"] == "Insert")
     {
      $first_name = mysqli_real_escape_string($object->connect, $_POST["first_name"]);
      $last_name = mysqli_real_escape_string($object->connect, $_POST["last_name"]);
      $image = $object->upload_file($_FILES["user_image"]);
      $query = "
      INSERT INTO users
      (first_name, last_name, image) 
      VALUES ('".$first_name."', '".$last_name."', '".$image."')
      ";
      $object->execute_query($query);
      echo 'Data Inserted';
     }
     if($_POST["action"] == "Fetch Single Data")
     {
      $output = '';
      $query = "SELECT * FROM users WHERE id = '".$_POST["user_id"]."'";
      $result = $object->execute_query($query);
      while($row = mysqli_fetch_array($result))
      {
       $output["first_name"] = $row['first_name'];
       $output["last_name"] = $row['last_name'];
       $output["image"] = '<img src="upload/'.$row['image'].'" class="img-thumbnail" width="50" height="35" />';
       $output["user_image"] = $row['image'];
      }
      echo json_encode($output);
     }
    
     if($_POST["action"] == "Edit")
     {
      $image = '';
      if($_FILES["user_image"]["name"] != '')
      {
       $image = $object->upload_file($_FILES["user_image"]);
      }
      else
      {
       $image = $_POST["hidden_user_image"];
      }
      $first_name = mysqli_real_escape_string($object->connect, $_POST["first_name"]);
      $last_name = mysqli_real_escape_string($object->connect, $_POST["last_name"]);
      $query = "UPDATE users SET first_name = '".$first_name."', last_name = '".$last_name."', image = '".$image."' WHERE id = '".$_POST["user_id"]."'";
      $object->execute_query($query);
      echo 'Data Updated';
      //echo $query;
     }
     
     if($_POST["action"] == "Delete")
     {
      $query = "DELETE FROM users WHERE id = '".$_POST["user_id"]."'";
      $object->execute_query($query);
      echo "Data Deleted";
     }
     
     if($_POST["action"] == "Search")
     {
      $search = mysqli_real_escape_string($object->connect, $_POST["query"]);
      $query = "
      SELECT * FROM users 
      WHERE first_name LIKE '%".$search."%' 
      OR last_name LIKE '%".$search."%' 
      ORDER BY id DESC
      ";
      //echo $query;
      echo $object->get_data_in_table($query);  
     }
     
    }
    ?>