pagination, PHP, database results, MySQL, web development
This example shows how to paginate database results using PHP and MySQL, improving user experience by limiting the number of records displayed on a page.
<?php
// Database connection
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Define how many results you want per page
$results_per_page = 10;
// Find out the number of results stored in database
$result = $conn->query("SELECT COUNT(id) AS total FROM your_table");
$row = $result->fetch_assoc();
$total_results = $row['total'];
// Determine number of pages available
$number_of_pages = ceil($total_results / $results_per_page);
// Determine which page number visitor is currently on
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
// Determine the SQL LIMIT starting number for the results on the displaying page
$starting_limit = ($page - 1) * $results_per_page;
// Retrieve the selected results from database
$result = $conn->query("SELECT * FROM your_table LIMIT " . $starting_limit . ',' . $results_per_page);
// Display the retrieved results
while ($row = $result->fetch_assoc()) {
echo "<div>";
echo "ID: " . $row['id'] . " - Name: " . $row['name'];
echo "</div>";
}
// Display the links to the pages
for ($page = 1; $page <= $number_of_pages; $page++) {
echo "<a href='your_script.php?page=" . $page . "'>" . $page . "</a> ";
}
// Close connection
$conn->close();
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?