Đây là hàm giúp bạn trình bày số trang tốt hơn và chuyên nghiệp hơn
Bạn từng làm quen về cách phân trang cho dữ liệu lấy từ database
Hôm nay mình sẽ giới thiệu cho các bạn 1 hàm phân trang sử lý chuyên nghiệp hơn
xem mã nguồn dưới:
<?
// +---------------------------------------------+
// | Author:billy_duc@yahoo.com |
// | WebSite:www.banmai.org,alezo.net |
// +---------------------------------------------+
function showpage($page,$url,$total,$maxpage,$show)
{
if ($page>$maxpage) {
$num_page=ceil($page/$maxpage);
$showpage=($num_page-1)*$maxpage;
$end=$showpage+$maxpage;
$showpage++;
}else
{
$thispage=1;
$showpage=1;
$end=$maxpage;
}
$startpage=$showpage;
for ($showpage;$showpage<$end+1;$showpage++)
{
if ($showpage<=$total) {
if ($page==$showpage) {
$list_page.="<font color='red'>".$showpage."</font> ";
}else {
$list_page.="<a href='$url?page=$showpage'>".$showpage."</a> ";
}
}
}
if ($num_page>1) {
$back=$startpage-1;
if ($num_page>2) {
$list_page1="<a href='$url?page=1'>First page</a> ";
}
$list_page1.="<a href='$url?page=$back'>Back</a> ";
}
if ($num_page<ceil($total/$maxpage)&&($total>$maxpage)) {
$next=$showpage;
$list_page2.=" <a href='$url?page=$next'>Next</a>";
$list_page2.=" <a href='$url?page=$total'>Last page</a>";
}
$list_page=$list_page1.$list_page.$list_page2;
switch ($show) {
case "str":
return $list_page;
break;
default:
echo $list_page;
break;
}
}
// Test thử :
$page=isset($_GET['page']) ? intval($_GET['page']):1;
showpage($page,"page.php",100,5,""); // print First page Back 11 12 13 14 15 Next Last page
?>
GET và POST xem bài trước
$page: Trang hiện tại.
$url: Tiên kết.
$total: Tổng số trang.
$maxpage: Số trang hiển thị.
$show: có 2 dạng hiển thị, "str" trả về dạng chuỗi, "" in luôn ra
Bạn có thể download file đính kèm về chạy thử là biết liền.