How to implement pagination to display page numbers in PHP?

In PHP, you can follow these steps to implement pagination for displaying page numbers:

Set the number of records displayed per page and the total number of records.

Calculate the total number of pages based on the total number of records.

3. Retrieve the current page number (via URL parameters or other methods).

Calculate the range of page numbers to be displayed based on the current page number and total number of pages.

5. Use a loop to output page number links.

Here is a simple example code demonstrating how to implement pagination to display page numbers.

<?php

$totalRecords = 100; // 总记录数量

$recordsPerPage = 10; // 每页显示的记录数量

$totalPages = ceil($totalRecords / $recordsPerPage); // 计算总页数

$currentpage = isset($_GET['page']) ? $_GET['page'] : 1; // 获取当前页数,默认为1

$paginationRange = 5; // 要展示的页码范围

$startPage = max(1, $currentpage - floor($paginationRange / 2));

$endPage = min($startPage + $paginationRange - 1, $totalPages);

echo "<ul>";

for ($i = $startPage; $i <= $endPage; $i++) {

    echo "<li><a href='?page=$i'>$i</a></li>";

}

echo "</ul>";

?>

This code will calculate the total number of pages based on the total number of records and the number of records displayed per page. It will then calculate the page numbers to be displayed based on the current page and the specified page range. Finally, it will use a loop to output the corresponding page links.

Please note that this is just a simple example, and the actual situation may be more complex. For example, you may need to handle out-of-range page numbers, display previous and next pages, etc. You can modify and expand according to your own needs.

广告
Closing in 10 seconds
bannerAds