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

Mary-Kate Olsen
Release: 2024-11-02 12:28:30
Original
998 people have browsed it

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>
Copy after login

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!

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