How can PHP be used to implement pagination in a script that displays database results?

To implement pagination in a script that displays database results, you can use PHP to limit the number of results displayed per page and provide navigation links to move between pages of results. This can be achieved by using the LIMIT clause in your SQL query to fetch a specific range of results based on the current page number and the number of results per page.

<?php
// Establish database connection
$connection = mysqli_connect('localhost', 'username', 'password', 'database');

// Define number of results per page
$results_per_page = 10;

// Determine current page number
if (isset($_GET['page'])) {
    $page = $_GET['page'];
} else {
    $page = 1;
}

// Calculate the starting result for the current page
$start_from = ($page - 1) * $results_per_page;

// Retrieve results from database with pagination
$query = "SELECT * FROM table_name LIMIT $start_from, $results_per_page";
$result = mysqli_query($connection, $query);

// Display results
while ($row = mysqli_fetch_assoc($result)) {
    echo $row['column_name'] . "<br>";
}

// Create pagination links
$query = "SELECT COUNT(*) AS total FROM table_name";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$total_pages = ceil($row['total'] / $results_per_page);

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

// Close database connection
mysqli_close($connection);
?>