Home >Database >Mysql Tutorial >How to Implement PHP and MySQL Pagination for Large Datasets?

How to Implement PHP and MySQL Pagination for Large Datasets?

Barbara Streisand
Barbara StreisandOriginal
2024-12-04 00:50:10555browse

How to Implement PHP and MySQL Pagination for Large Datasets?

PHP and MySQL Pagination

One common task for web applications is to display large datasets in a paginated format, allowing users to view a limited number of results per page. This can enhance user experience and performance.

Consider a MySQL query that retrieves all records from the 'redirect' table filtered by a user ID:

SELECT * FROM redirect WHERE user_id = '".$_SESSION['user_id']."' ORDER BY 'timestamp'

To paginate this query such that it shows 10 results per page, follow these steps:

<?php

// Insert your MySQL connection code here

// Set the number of results per page
$perPage = 10;

// Get the current page number from GET request (or default to 1)
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;

// Calculate the starting record for the specified page
$startAt = $perPage * ($page - 1);

// Count the total number of records in the table
$query = "SELECT COUNT(*) as total FROM redirect
WHERE user_id = '".$_SESSION['user_id']."'";
$r = mysql_fetch_assoc(mysql_query($query));

// Calculate the total number of pages
$totalPages = ceil($r['total'] / $perPage);

// Generate the pagination links
$links = "";
for ($i = 1; $i <= $totalPages; $i++) {
  $links .= ($i != $page ) 
            ? "<a href='index.php?page=$i'>Page $i</a> "
            : "$page ";
}

// Execute the paginated query
$r = mysql_query($query);

$query = "SELECT * FROM `redirect`
WHERE `user_id`= '".$_SESSION['user_id']."' 
ORDER BY 'timestamp' LIMIT $startAt, $perPage";

$r = mysql_query($query);

// Display the results using the pagination system
echo $links; // Show links to other pages
?>

The above is the detailed content of How to Implement PHP and MySQL Pagination for Large Datasets?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn