What steps can be taken to ensure accurate pagination and data display in PHP scripts when fetching records from a database?

When fetching records from a database in PHP scripts for pagination, it is important to properly handle the pagination logic to ensure accurate display of data. This involves calculating the total number of records, determining the number of records to display per page, and adjusting the SQL query accordingly. Additionally, the pagination links should be generated dynamically based on the total number of pages.

// Calculate total number of records
$totalRecords = $pdo->query("SELECT COUNT(*) FROM table")->fetchColumn();

// Define number of records to display per page
$recordsPerPage = 10;

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

// Get current page number
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
    $currentPage = $_GET['page'];
} else {
    $currentPage = 1;
}

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

// Fetch records for the current page
$stmt = $pdo->prepare("SELECT * FROM table LIMIT :offset, :recordsPerPage");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':recordsPerPage', $recordsPerPage, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();

// Display records
foreach ($rows as $row) {
    // Display record data
}

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