This topic explains how pagination is implemented inside a PHP CRUD class to efficiently retrieve large datasets by dividing records into manageable pages.
Pagination works by calculating an offset based on the current page number and the number of records per page. This offset is then used with SQL LIMIT.
// PHP CRUD class with pagination method
conn = $db;
}
public function selectWithPagination($page = 1, $limit = 5) {
$offset = ($page - 1) * $limit;
$stmt = $this->conn->prepare("SELECT * FROM ".$this->table." LIMIT ?, ?");
$stmt->bind_param("ii", $offset, $limit);
$stmt->execute();
$result = $stmt->get_result();
return $result->fetch_all(MYSQLI_ASSOC);
}
}
// Using the pagination method
$conn = new mysqli("localhost", "username", "password", "myDB");
$user = new User($conn);
$pageData = $user->selectWithPagination(2, 5);
foreach($pageData as $row) {
echo $row['id']." - ".$row['first_name']."
";
}
?>
The code fetches five records starting from the second page. The calculated offset ensures only the required records are retrieved and displayed.
Change the page number and limit values to observe how different record sets are loaded dynamically.