Learn how to implement pagination in php

0
2904

In this tutorial today we will learn how to implement pagination in php.Pagination in PHP helps to access multiple pages instead of accessing them one by one seperately.

  • To learn how to implement pagination in php follow the steps given below :

  1. First of all download and install xampp server in your machine .
  2. Now go to your xampp folder i.e the folder you have installed your xampp .
  3. Open the xampp control pannel from this xampp folder and you will get the following window :
  4. pagination

  5. Now start the Apache and MySQL modules as shown in the above image .
  6. Let’s create a database which we will be accessing in this session.
  7. Open up your browser and enter the following url : localhost/phpmyadmin and you will get the following window :
  8. learn how to implement pgination in php

  9. Now enter username and password and click on the GO button , you will be navigated to the following window , where you have to click on the Database tab and then enter your database name and finally click on the create button and your database is generated in the database list at the left hand side as shown in the image :
  10. pagination

  11. Now select the database from the list then you will get the following window where you have to select the SQL tab as shown in the image :
  12. pagination in php

  13. After selecting the SQL tab you will get the query box where you have to write the following query to create a table :
  14. CREATE TABLE IF NOT EXISTS `fruits` (
      `id` int(5) NOT NULL AUTO_INCREMENT,
      `name` varchar(21) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
    

  15. Here is the screen shot for the code :
  16. implementation of pagenation in php

  17. After writing the query click on the GO button .
  18. Now again click on the SQL tab where a query box will appear and insert the following values into the table :
  19. INSERT INTO `fruits` (`id`, `name`) VALUES
    (1, 'Mango'),
    (2, 'Jackfruit'),
    (3, 'Guava'),
    (4, 'Apple'),
    (5, 'Strawberry'),
    (6, 'Banana'),
    (7, 'Custard Apple'),
    (8, 'Musk Melon'),
    (9, 'Water Melon'),
    (10, 'Pineapple');
    

  20. Here is the screen shot for the code :
  21. Insert values in table

  22. After that click on the GO button to execute the query.
  23. Now we have the database as follows:
  24. database

  25. Now create a Folder inside the xampphtdocs and name the folder for example as testing .
  26. testing folder created in xampp

  27. Inside the testing folder create a file called as fruit.php:
  28. pagination implementation in php

  29. Now write the following code as per instruction inside the fruit.php file .
  30. <?php
    //Local host connection
    mysql_connect("localhost","root","1234") or die (mysql_error());
    mysql_select_db("ijdb") or die (mysql_error());
    //select the table 
    $sql = mysql_query("SELECT name from fruits");
    
    //  Logic //
    // Get total of Num rows from the database query
    $nr = mysql_num_rows($sql);
    // Get pn from URL vars if it is present 
    if (isset($_GET['pn'])) { 
        // filter everything but numbers for security(new)
        $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); 
        // filter everything but numbers for security(deprecated)
        $pn = ereg_replace("[^0-9]", "", $_GET['pn']); 
    } else { 
        // If the pn URL variable is not present force it to be value of page number 1
        $pn = 1;
    }
    //This is where we set how many database items to show on each page 
    $itemsPerPage = 1; 
    // Get the value of the last page in the pagination result set
    $lastPage = ceil($nr / $itemsPerPage);
    // Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
    if ($pn < 1) { 
    // If it is less than 1
        $pn = 1; 
    // force if to be 1
        } 
    // if it is greater than $lastpage
    else if ($pn > $lastPage) { 
    // force it to be $lastpage's value
        $pn = $lastPage; 
    }
    // This creates the numbers to click in between the next and back buttons
    $centerPages = "";
    $sub1 = $pn - 1;
    $sub2 = $pn - 2;
    $add1 = $pn + 1;
    $add2 = $pn + 2;
    if ($pn == 1) {
        $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1.'">' . $add1 . '</a> &nbsp;';
    } else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
        $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    } else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
        $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
    } else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
        $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
        $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';}
    // This line sets the "LIMIT" range. the 2 values we place to choose a range of rows from database in our query
    $limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage; 
    // Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
    // $sql2 is what we will use to fuel our while loop statement below
    $sql2 = mysql_query("SELECT name FROM fruits $limit"); 
    // Logic Ends //
    //  Pagination Display Setup Begins
     // Initialize the pagination output variable
    $paginationDisplay = "";
    // This code runs only if the last page variable is not equal to 1,else we dont need pagination
    if ($lastPage != "1"){
        // This shows the user what page they are on, and the total number of pages
        $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
        // If we are not on page 1 we can place the Back button
        if ($pn != 1) {
            $previous = $pn - 1;
           $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
        } 
        // Lay in the clickable numbers display here between the Back and Next links
        $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
        // If we are not on the very last page we can place the Next button
        if ($pn != $lastPage) {
            $nextPage = $pn + 1;
           $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
        } 
    }
    //// END Pagination Display Setup
    // Build the Output Section Here
    $outputList = '';
    while($row = mysql_fetch_array($sql2)){ 
    
        
        $name = $row["name"];
        
    
        $outputList .= '<h1>' . $name . '</h1><br />';
        
    } // close while loop
    ?>
    Now we have to give heading and the styling to our page as follows
    
    <html>
    <head>
    <title>Pagination</title>
    <style type="text/css">
    <!--
    .pagNumActive {
        color: #000;
        border:#060 1px solid; background-color: #D2FFD2; padding-left:3px; padding-right:3px;
    }
    .paginationNumbers a:link {
        color: #000;
        text-decoration: none;
        border:#999 1px solid; background-color:#F0F0F0; padding-left:3px; padding-right:3px;
    }
    .paginationNumbers a:visited {
        color: #000;
        text-decoration: none;
        border:#999 1px solid; background-color:#F0F0F0; padding-left:3px; padding-right:3px;
    }
    .paginationNumbers a:hover {
        color: #000;
        text-decoration: none;
        border:#060 1px solid; background-color: #D2FFD2; padding-left:3px; padding-right:3px;
    }
    .paginationNumbers a:active {
        color: #000;
        text-decoration: none;
        border:#999 1px solid; background-color:#F0F0F0; padding-left:3px; padding-right:3px;
    }
    -->
    </style>
    </head>
    <body>
       <div style="margin-left:64px; margin-right:64px;">
         <h2>Total Items: <?php echo $nr; ?></h2>
      </div> 
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;">
              <?php echo $paginationDisplay; ?></div>
      <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;">
              <?php echo $paginationDisplay; ?></div>
    </body>
    </html>
    

  31. Here are the screen shots for the code :
  32. fruits.php
    pagination code
    php pagination

    pagination

    10
    11
    pagination in php
    learn php
    php implementation
    pagenation
    code for pagenation
    17
    18
    learn how to implement pagination in php
    pagination code

  33. Now open up the browser and enter the following url : localhost/testing/fruits.php and you will have the following output :
  34. output of pagenation

  35. Thus we have successfully learnt how to implement pagination in php .

LEAVE A REPLY

Please enter your comment!
Please enter your name here