Home >Backend Development >PHP Tutorial >How to Implement Pagination with PHP and MySQL for Large Datasets?

How to Implement Pagination with PHP and MySQL for Large Datasets?

DDD
DDDOriginal
2024-11-03 23:58:30719browse

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

  • $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!

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