Developer Snippet Diary

Custom pagination in PHP using PDO

Here is complete code for pagination.

Custom pagination in PHP using PDO

<style>
.pagination a, .pagination span {
  color: black;
  float: left;
  padding: 8px 16px;
  text-decoration: none;
  transition: background-color .3s;
  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>
<?php
// Pagination configuration
$servername = "localhost";
$username = "root";
$password = "";
$db="sp_ypages";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

$recordsPerPage = 10; // Number of records to display per page
$page = isset($_GET['page']) ? $_GET['page'] : 1; // Current page number

// Calculate the offset for the SQL query
$offset = ($page - 1) * $recordsPerPage;

// Query to retrieve data with pagination
$sql = "SELECT * FROM businesses LIMIT :limit OFFSET :offset";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':limit', $recordsPerPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Query to count the total number of records
$countSql = "SELECT COUNT(*) AS count FROM businesses";
$countStmt = $conn->query($countSql);
$totalRecords = $countStmt->fetch(PDO::FETCH_ASSOC)['count'];

// Calculate the total number of pages
$totalPages = ceil($totalRecords / $recordsPerPage);

?>
<!-- Display the HTML table with pagination -->
<table style="font-family: cursive;">
 <thead>
   <tr>
     <th>Name</th>
     <th>City</th>
   </tr>
 </thead>
 <tbody>
   <?php foreach ($result as $key => $val) { ?>
   <tr>
     <td><?php echo $val['name'];?></td>
     <td><?php echo $val['city'];?></td>
   </tr>
   <?php } ?>
 </tbody>
</table>

<!-- Display the pagination links -->
<div class="pagination">
 <?php
 $maxPagesToShow = 10; // Maximum number of pages to display in the pagination

 // Previous page link
 if ($page > 1) {
     echo '<a href="?page='.($page - 1).'">Previous</a>';
 }
 if ($page > 1) {
     echo '<a href="?page=1">1</a>';
 }

 // Page links
 $startPage = max(1, $page - floor($maxPagesToShow / 2));
 $endPage = min($startPage + $maxPagesToShow - 1, $totalPages);

 for ($i = $startPage; $i <= $endPage; $i++) {
     if ($i == $page) {
         echo '<span class="current">'.$i.'</span>';
     } else {
         echo '<a href="?page='.$i.'">'.$i.'</a>';
     }
 }

 // Ellipsis if there are more pages
 if ($endPage < $totalPages) {
     echo '<span class="ellipsis">...</span>';
     echo '<a href="?page='.$totalPages.'">'.$totalPages.'</a>';
 }

 // Next page link
 if ($page < $totalPages) {
     echo '<a href="?page='.($page + 1).'">Next</a>';
 }
 ?>
</div>
Posted by: R GONDAL
Email: rizikmw@gmail.com