How do I paginate database results in PHP?

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(); ?>

pagination PHP database results MySQL web development