帮我用php写一个分页.要求:适用于所有的分页功能
时间: 2024-06-10 21:06:02 浏览: 150
php实现分页
好的,我可以为您提供一个通用的 PHP 分页函数,适用于所有需要分页的情况。以下是示例代码:
```
function getPage($total_records, $page_size, $current_page, $url) {
$total_pages = ceil($total_records / $page_size);
$prev = $current_page - 1;
$next = $current_page + 1;
// Set page limit to prevent user from exceeding limit
if ($current_page > $total_pages) {
$current_page = $total_pages;
} elseif ($current_page < 1) {
$current_page = 1;
}
// Prev button
if ($current_page == 1) {
$navigation .= '<span class="disabled">Prev</span>';
} else {
$navigation .= '<a href="'.$url.'page='.$prev.'">Prev</a>';
}
// Numeric buttons
$numeric_links = '';
for ($i = 1; $i <= $total_pages; $i++) {
if ($i == $current_page) {
$numeric_links .= '<span class="current">'.$i.'</span>';
} else {
$numeric_links .= '<a href="'.$url.'page='.$i.'">'.$i.'</a>';
}
}
$navigation .= '<span class="numeric">'.$numeric_links.'</span>';
// Next button
if ($current_page == $total_pages) {
$navigation .= '<span class="disabled">Next</span>';
} else {
$navigation .= '<a href="'.$url.'page='.$next.'">Next</a>';
}
return $navigation;
}
```
调用该函数时,需要传入总记录数 `$total_records`、每页显示的记录数 `$page_size`、当前页码 `$current_page` 和分页链接 `$url`。函数会返回一个 HTML 字符串,包含分页导航。
使用示例:
```
$total_records = 1000; // 总记录数
$page_size = 10; // 每页显示的记录数
$current_page = $_GET['page'] ?: 1; // 当前页码
$url = 'http://example.com/article.php?'; // 分页链接
$navigation = getPage($total_records, $page_size, $current_page, $url);
echo $navigation;
```
该函数将输出一个 HTML 字符串,包含类似于以下内容的分页导航:
```
Prev <span class="numeric"><a href="http://example.com/article.php?page=1">1</a><a href="http://example.com/article.php?page=2">2</a><a href="http://example.com/article.php?page=3">3</a> ... <a href="http://example.com/article.php?page=98">98</a><a href="http://example.com/article.php?page=99">99</a><a href="http://example.com/article.php?page=100">100</a></span> Next
```
阅读全文