Home  >  Article  >  Backend Development  >  How to Implement Pagination in PHP & MySQL for a \'redirect\' Table?

How to Implement Pagination in PHP & MySQL for a \'redirect\' Table?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 12:28:30999browse

How to Implement Pagination in PHP & MySQL for a 'redirect' Table?

PHP & MySQL Pagination: A Comprehensive Guide

Problem:

You have a MySQL query that retrieves data from the 'redirect' table based on a specific 'user_id' and sorts the results by 'timestamp'. You need to implement pagination to display 10 results per page.

Solution:

To perform pagination in PHP:

<code class="php"><?php

// Insert your MySQL connection code here

// Define variables
$perPage = 10;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$startAt = $perPage * ($page - 1);

// Get total number of rows
$query = "SELECT COUNT(*) as total FROM redirect
WHERE user_id = '".$_SESSION['user_id']."'";
$r = mysql_fetch_assoc(mysql_query($query));

// Calculate total number of 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 query with pagination applied
$query = "SELECT * FROM 'redirect'
WHERE 'user_id'= \''.$_SESSION['user_id'].' \' 
ORDER BY 'timestamp' LIMIT $startAt, $perPage";

$r = mysql_query($query);

// Display results ...

// Echo pagination links
echo $links; // show links to other pages</code>

The above is the detailed content of How to Implement Pagination in PHP & MySQL for a \'redirect\' Table?. 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