Home > Article > Backend Development > How to Implement Pagination with PHP and MySQL for Large Datasets?
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:
<code class="php"><?php // MySQL connection code (not shown for brevity) // Set pagination parameters $perPage = 10; $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1; $startAt = $perPage * ($page - 1); // Get total number of records $query = "SELECT COUNT(*) as total FROM redirect WHERE user_id = '".$_SESSION['user_id']."'"; $r = mysql_fetch_assoc(mysql_query($query)); // Calculate total pages $totalPages = ceil($r['total'] / $perPage); // Generate pagination links $links = ""; for ($i = 1; $i <= $totalPages; $i++) { $links .= ($i != $page ) ? "<a href='index.php?page=$i'>Page $i</a> " : "$page "; } // Execute paginated query $query = "SELECT * FROM 'redirect' WHERE 'user_id'= \''.$_SESSION['user_id'].' \' ORDER BY 'timestamp' LIMIT $startAt, $perPage"; $r = mysql_query($query); // Display results and pagination links // ... echo $links; // display pagination links ?></code>
Explanation
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!