How can one efficiently handle pagination in PHP when fetching data from a database?
When fetching data from a database in PHP, pagination can be efficiently handled by using the LIMIT clause in the SQL query to retrieve a specific subset of data based on the page number and number of items per page. By calculating the offset based on the current page number and items per page, we can retrieve the correct data subset for each page.
// Set the current page number and number of items per page
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$itemsPerPage = 10;
// Calculate the offset for the SQL query
$offset = ($page - 1) * $itemsPerPage;
// Fetch data from the database using LIMIT and OFFSET
$query = "SELECT * FROM table_name LIMIT $itemsPerPage OFFSET $offset";
$result = mysqli_query($connection, $query);
// Loop through the result set and display the data
while ($row = mysqli_fetch_assoc($result)) {
// Display data here
}
Related questions
-
PHP input fields naming conventions
-
comparison operators PHP scripts potential consequences
-
PHP MySQL search