How to implement pagination for a MySQL query in PHP?

Barbara Streisand
Release: 2024-11-03 17:13:03
Original
978 people have browsed it

How to implement pagination for a MySQL query in PHP?

Pagination in PHP Using MySQL Queries

Pagination allows breaking down large datasets into smaller, manageable pages, making it convenient for users to navigate and access data. This example focuses on implementing pagination for a MySQL query in a PHP script.

To paginate 10 results per page, you can utilize the following code as a starting point:

<code class="php"><?php

// Establish MySQL connection

$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 ";
}


$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 results as desired

echo $links; // Display links to other pages</code>
Copy after login

This code calculates the total number of pages, generates page links, and returns only the desired results for the current page. You can then display these results in your web page.

The above is the detailed content of How to implement pagination for a MySQL query in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template