How can pagination be implemented in PHP to display only a certain number of records at a time?

Pagination in PHP can be implemented by using LIMIT and OFFSET clauses in SQL queries to retrieve a specific number of records at a time. By calculating the total number of records and the number of records to display per page, you can determine the OFFSET value for each page. This allows you to display only a certain number of records at a time, improving performance and user experience.

<?php
// Establish database connection
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');

// Determine current page
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$records_per_page = 10;
$offset = ($page - 1) * $records_per_page;

// Query to retrieve records with pagination
$stmt = $pdo->prepare("SELECT * FROM table_name LIMIT :offset, :records_per_page");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':records_per_page', $records_per_page, PDO::PARAM_INT);
$stmt->execute();

// Display records
while ($row = $stmt->fetch()) {
    // Display record data
}

// Pagination links
$total_records = $pdo->query("SELECT COUNT(*) FROM table_name")->fetchColumn();
$total_pages = ceil($total_records / $records_per_page);

for ($i = 1; $i <= $total_pages; $i++) {
    echo "<a href='?page=$i'>$i</a> ";
}
?>