What are the best practices for structuring PHP code to efficiently handle pagination and display data from a database?

When handling pagination and displaying data from a database in PHP, it is important to efficiently structure your code to minimize database queries and optimize performance. One way to achieve this is by using SQL LIMIT and OFFSET clauses to fetch only the necessary data for each page of results.

<?php

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Define pagination variables
$limit = 10; // Number of records per page
$page = isset($_GET['page']) ? $_GET['page'] : 1; // Current page number

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

// Prepare and execute the SQL query with LIMIT and OFFSET
$stmt = $pdo->prepare("SELECT * FROM your_table LIMIT :limit OFFSET :offset");
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();

// Fetch and display the data
while ($row = $stmt->fetch()) {
    // Display data from each row
}

// Display pagination links
// You can use a function to generate pagination links based on the total number of records in the database