PHP Pagination Tutorial: Simple Steps
To implement pagination, you can use the built-in PHP function array_slice() to paginate an array. The specific steps are as follows:
- Set the number of data items displayed per page and the current page number. For example, display 10 data items per page with the current page number as $page.
- Retrieve all data from a database or other data source and store it as an array, for example $items.
- You can calculate the total number of data records $totalCount using the built-in PHP function count().
- Calculate the total number of pages $totalPages by rounding up the result of $totalCount divided by $perPage using ceil().
- Perform pagination on the array using array_slice($items, ($page – 1) * $perPage, $perPage) to obtain the data for the current page.
- Display the data on the current page by iterating through it.
- Generate a pagination bar based on the total number of pages and the current page number. You can create the navigation bar by combining HTML and PHP, such as using a for loop to generate clickable page buttons with links.
Here is an example code:
<?php
// 定义每页显示的数据条数
$perPage = 10;
// 获取当前页码
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// 从数据库或其他数据源获取所有数据,并保存为一个数组
$items = array(/* 数据数组 */);
// 计算总数据条数
$totalCount = count($items);
// 计算总页数
$totalPages = ceil($totalCount / $perPage);
// 对数组进行分页操作,得到当前页的数据
$currentPageItems = array_slice($items, ($page - 1) * $perPage, $perPage);
// 遍历当前页的数据进行显示
foreach ($currentPageItems as $item) {
// 显示数据
}
// 生成分页导航栏
echo '<div class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
echo '<a href="?page=' . $i . '">' . $i . '</a> ';
}
echo '</div>';
?>
The code above calculates the total number of pages and the current page number, then uses the array_slice() function to paginate an array, and generates a pagination bar using a for loop. Depending on the specific situation, you may need to make modifications and adjustments as needed.