How can the code be refactored to implement pagination for displaying data on multiple pages instead of one?
To implement pagination for displaying data on multiple pages instead of one, we can modify the query to limit the number of results fetched per page and calculate the offset based on the current page number. We can also add navigation links to allow users to navigate between pages.
<?php
// Define the number of results per page
$results_per_page = 10;
// Get the current page number, default to 1
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// Calculate the offset for the query
$offset = ($page - 1) * $results_per_page;
// Modify your query to limit results based on offset and results per page
$query = "SELECT * FROM your_table LIMIT $offset, $results_per_page";
// Execute the query and display results
// Add navigation links to navigate between pages
$total_pages = ceil($total_results / $results_per_page);
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
?>
Keywords
Related Questions
- How can the switch statement in PHP be utilized to handle multiple conditions more efficiently?
- What are the potential consequences of relying on RegisterGlobals being set to "on" in PHP scripts?
- Are there any best practices to follow when writing PHP scripts to interact with MySQL databases for simple data manipulation tasks?