How to write a simple pagination code in PHP?
Here is a straightforward example of PHP pagination code:
<?php
// 设置每页显示的记录数
$per_page = 10;
// 获取当前页码
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;
// 假设有一个数组 $data 存储了要分页显示的数据
$data = array(
// 数据内容
);
// 计算总记录数和总页数
$total_records = count($data);
$total_pages = ceil($total_records / $per_page);
// 根据当前页码计算起始位置
$start = ($current_page - 1) * $per_page;
// 获取当前页显示的数据
$display_data = array_slice($data, $start, $per_page);
// 输出当前页的数据
foreach ($display_data as $item) {
echo $item . "<br>";
}
// 输出分页导航栏
echo "<div class='pagination'>";
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
echo "</div>";
?>
In the above code, $data is the collection of data to be paginated, $per_page is the number of records to be displayed per page. By calculating the total number of records $total_records and total pages $total_pages, then based on the current page number $current_page, calculating the starting position $start, and using the array_slice function to retrieve the data $display_data to be displayed on the current page. Finally, using a foreach loop to output the data on the current page, and displaying a pagination navigation bar so that users can switch between different page numbers by clicking.