Pagination is essential for managing large datasets efficiently, allowing users to browse data in smaller, manageable pages. MySQL provides two keywords, LIMIT and OFFSET, to implement pagination.
The provided code uses a fixed limit of 4 items per page, which works for a predetermined database size. However, the goal is to create dynamic pagination without hard-coding page offsets.
To create dynamic pagination, we need to:
To determine if a "NEXT PAGE" link should be displayed, we need to know the total number of pages:
Using the current page number ($page) and the total pages ($page_count), you can dynamically generate links for pagination. For instance, a loop could iterate over the pages and create links for each one. The current page would be displayed as text, while other pages would be displayed as links.
// Get the current page number from the URL $page = 1; if (isset($_GET['page'])) { $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT); if ($page === false) { $page = 1; } } // Set the number of items to display per page $items_per_page = 4; // Build the query $offset = ($page - 1) * $items_per_page; $sql = "SELECT * FROM menuitem LIMIT $offset, $items_per_page"; // Execute the query and fetch the results // Calculate the total number of rows $sql_count = "SELECT COUNT(*) AS row_count FROM menuitem"; $result_count = mysqli_query($con, $sql_count); $row_count = mysqli_num_rows($result_count); $page_count = (int)ceil($row_count / $items_per_page); // Check if the requested page is in range if ($page > $page_count) { // Display an error or set the page to 1 } // Later, when outputting the page, you can use $page and $page_count to generate pagination links
Das obige ist der detaillierte Inhalt vonWie implementiert man dynamische Paginierung in MySQL mit LIMIT und OFFSET?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!