Simple Pagination System in PHP

Pagination is required in web project commonly. Whenever we get a huge amount of data access from database to display then we can’t show it on single page.

Loading a huge data on single page slow down a webpage and typical for a user to see all content of webpage by scrolling. This causes a big problem when a major level project in php with a heavy data or records. Therefore a technique used in the php is pagination by which we set limitation on data display on single page.

Pagination decreases the loading time of webpage and load the faster from database. In this tutorial, we are going to create simple pagination system in php with mysql. Here I am using a class file for pagination and make it simple as much as possible.

Simple pagination in PHP - PHPCluster

Demo

Here we are using 2 files for pagination.

1) Index.php   //page to display paginated data
3) Style.css      //css file for pagination layout

Database details:
DB name =”test”
Table name =”pagination”

Let us see in detail:

index.php

<link rel="stylesheet" type="text/css" href="style.css">
<?php 
$dbname = "test";
$dbuser = "root";
$dbpw    = "";
$dbhost = "localhost";
$conn = mysqli_connect($dbhost, $dbuser, $dbpw, $dbname);
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


$limit      = 3;  
$page       = isset($_GET['page']) ? $_GET['page'] : 1; //or somewhere
$start_from = ($page-1) * $limit;  
  
$sql = mysqli_query($conn, "SELECT * FROM pagination LIMIT $start_from, $limit");  
?>  
<table class="table table-bordered table-striped">  
<thead>  
<tr>  
<th>ID</th>  
<th>Name</th>  
<th>Phone</th>  
</tr>  
<thead>  
<tbody>  
<?php  
while($row = mysqli_fetch_array($sql)) {  ?>  
            <tr>  
            <td><?php echo $row["id"]; ?></td>  
            <td><?php echo $row["name"]; ?></td>  
			<td><?php echo $row["phone"]; ?></td>  
            </tr>  
<?php  }  ?>  
</tbody>  
</table>  

<?php  
$sql = mysqli_query($conn, "SELECT id FROM pagination");  
$total_records  = mysqli_num_rows($sql);  

$total_pages = ceil($total_records / $limit);
  
//start pagination  
$PaginationLinks = "<ul class='pagination'>";  

for ($i=1; $i<=$total_pages; $i++) {  
             $PaginationLinks .= "<li><a href='".$_SERVER['PHP_SELF']."?page=".$i."'>".$i."</a></li>";  
};  
$PaginationLinks .= "</ul>";  
//end pagination

//show pagination
echo $PaginationLinks;
?>

Style.css

.pagination li{
  display: inline-block;
}

.pagination li{
    padding: 5px;
    margin: 5px;
    background-color: #f44336!important;
	
}

.pagination li a {
  color: #fff!important;
  float: left;
  padding: 5px 10px;
  text-decoration: none;
} 

[sociallocker]Download[/sociallocker]Finally, we have created a script for pagination in PHP. How simple is it. That’s it.