PHP Pagination


What is Pagination?

Pagination in PHP refers to the process of dividing a large set of data into smaller, more manageable sections called "pages." It is commonly used in web applications to display a limited number of records or results per page, allowing users to navigate through the data easily.

Pagination is essential when dealing with large data sets because displaying all the records on a single page can lead to performance issues and an overwhelming user interface. By implementing pagination, you can improve the user experience and optimize the performance of your application.

PHP program to pagination

  • Create a new PHP file in your working location and save it with your desired name.

  • Here we are using studentdata table with 121 records in localhost database.

Example

Here is an example for implementing pagination in PHP for displaying 10 records per each page of student data from a database.

<!DOCTYPE html>
<html>
<head>
   <style>
     /* Grid styles */
     .grid-container {
       display: grid;
       grid-template-columns: repeat(3, 1fr);
       grid-gap: 10px;
       margin-bottom: 20px;
     }

     .grid-item {
       background-color: #f2f2f2;
       padding: 10px;
       text-align: center;
     }

     /* Table styles */
     table {
       border-collapse: collapse;
       width: 100%;
     }

     th, td {
       padding: 8px;
       text-align: left;
       border-bottom: 1px solid #ddd;
     }

     th {
       background-color: #4CAF50;
       color: white;
     }

     /* Pagination styles */
     .pagination {
       display: inline-block;
     }

     .pagination a {
       color: black;
       float: left;
       padding: 8px 16px;
       text-decoration: none;
       border: 1px solid #ddd;
     }

     .pagination a.active {
       background-color: #4CAF50;
       color: white;
       border: 1px solid #4CAF50;
     }

     .pagination a:hover:not(.active) {
       background-color: #ddd;
     }
   </style>
</head>
<body>
   <?php
   // Database connection details
   $servername = "localhost";
   $username = "root";
   $password = "";
   $dbname = "assignments";

   // Create connection
   $conn = new mysqli($servername, $username, $password, $dbname);

   // Check connection
   if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
   }

   // Number of records per page
   $recordsPerPage = 10;

   // Current page number
   if (isset($_GET['page'])) {
     $currentPage = $_GET['page'];
   } else {
     $currentPage = 1;
   }

   // Calculate the starting record index
   $startFrom = ($currentPage - 1) * $recordsPerPage;

   // Fetch student data with pagination
   $sql = "SELECT * FROM studentdata LIMIT $startFrom, $recordsPerPage";
   $result = $conn->query($sql);

   if ($result->num_rows > 0) {
     // Display student data
     echo "<div class='grid-container'>";
     echo "<div class='grid-item'><strong>ID</strong><
/div>";
     echo "<div class='grid-item'><strong>Name</strong><
/div>";
     echo "<div class='grid-item'><strong>Age</strong><
/div>";

     while ($row = $result->fetch_assoc()) {
       echo "<div class='grid-item'>" . $row["id"] . "</div>";
       echo "<div class='grid-item'>" . $row["name"] . "</div>";
       echo "<div class='grid-item'>" . $row["age"] . "</div>";
     }

     echo "</div>";
   } else {
     echo "No records found.";
   }

   // Pagination links
   $sql = "SELECT COUNT(*) AS total FROM studentdata";
   $result = $conn->query($sql);
   $row = $result->fetch_assoc();
   $totalRecords = $row["total"];
   $totalPages = ceil($totalRecords / $recordsPerPage);

   echo "<div class='pagination'>";

   if ($totalPages > 1) {
     for ($i = 1; $i <= $totalPages; $i++) {
       if ($i == $currentPage) {
         echo "<a class='active' href='?page=$i'>$i</a> ";
       } else {
         echo "<a href='?page=$i'>$i</a> ";
       }
     }
   }

   echo "</div>";

   // Close the connection
   $conn->close();
   ?>
</body>
</html>

Output

Explanation 

The first part of the code establishes a database connection using the provided server name, username, password, and database name. It then checks if the connection was successful. Next, it sets the number of records to display per page and determines the current page number based on the URL parameter. It calculates the starting record index using the current page and the records per page value. The code then executes a database query to fetch the student data using the LIMIT clause to retrieve only the relevant records for the current page. It iterates through the query result and displays the student data in a grid layout.

The second part of the code handles pagination. It performs another database query to determine the total number of records in the "studentdata" table. It calculates the total number of pages by dividing the total number of records by the records per page value and rounding up. The code then generates the pagination links using a loop. If the total number of pages is greater than 1, it generates a link for each page. The current page is highlighted with an "active" class. Finally, the database connection is closed, and the HTML code is closed. Overall, this code retrieves and displays student data with pagination and provides navigation links to switch between pages.

Conclusion

The PHP code demonstrates an implementation of pagination in PHP. It utilizes MySQL database to fetch a subset of student data and display it in a grid layout. The code calculates the total number of pages based on the number of records per page and generates pagination links accordingly. Users can navigate through the data by clicking on the page links. This implementation improves the user experience by dividing large datasets into manageable sections, enhancing performance and preventing overwhelming UI. It showcases the basic steps involved in implementing pagination, including establishing a database connection, retrieving data with pagination, and generating pagination links dynamically.

Updated on: 01-Aug-2023

865 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements