How can PHP be used to display database records on a website with pagination?

To display database records on a website with pagination using PHP, you can retrieve records from the database, limit the number of records displayed per page, and provide navigation links for users to navigate through different pages of records.

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Define number of records per page
$records_per_page = 10;

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

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

// Retrieve records from the database with pagination
$sql = "SELECT * FROM table_name LIMIT $start_from, $records_per_page";
$result = $conn->query($sql);

// Display records on the website
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
}

// Display pagination links
$sql = "SELECT COUNT(id) AS total FROM table_name";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total_records = $row['total'];
$total_pages = ceil($total_records / $records_per_page);

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

// Close database connection
$conn->close();
?>