Pagination with PHP and MySQL
Paginating large datasets is a common task when designing responsive web applications. This article will demonstrate a method for implementing pagination with PHP and MySQL, allowing you to display a limited number of results per page.
Specifically, we aim to paginate the results of a hypothetical MySQL query that retrieves records from a table called 'redirect' based on a 'user_id' passed through a PHP session.
Code Implementation
To implement pagination, we can leverage the following PHP script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <code class = "php" ><?php
$perPage = 10;
$page = (isset( $_GET [ 'page' ])) ? (int) $_GET [ 'page' ] : 1;
$startAt = $perPage * ( $page - 1);
$query = "SELECT COUNT(*) as total FROM redirect WHERE user_id = '" . $_SESSION ['user_id ']."' ";
$r = mysql_fetch_assoc(mysql_query( $query ));
$totalPages = ceil ( $r [ 'total' ] / $perPage );
$links = "" ;
for ( $i = 1; $i <= $totalPages ; $i ++) {
$links .= ( $i != $page )
? "<a href='index.php?page=$i'>Page $i</a> "
: "$page " ;
}
$query = "SELECT * FROM 'redirect' WHERE 'user_id'= \''.$_SESSION['user_id'].' \' ORDER BY 'timestamp' LIMIT $startAt, $perPage" ;
$r = mysql_query( $query );
echo $links ;
?></code>
|
Copy after login
Explanation
- $perPage defines how many records to display per page.
- $page represents the current page being displayed.
- $startAt calculates the starting index of records for the current page.
- The COUNT(*) query calculates the total number of records to determine the number of pages required.
- Pagination links are generated with $links, and the active page is highlighted.
- Finally, a paginated MySQL query is executed, offsetting the results by $startAt and limiting the number of rows returned to $perPage.
The above is the detailed content of How to Implement Pagination with PHP and MySQL for Large Datasets?. For more information, please follow other related articles on the PHP Chinese website!