Skip to content

Instantly share code, notes, and snippets.

@weishuaiwang
Created October 29, 2012 02:41
Show Gist options
  • Save weishuaiwang/3971156 to your computer and use it in GitHub Desktop.
Save weishuaiwang/3971156 to your computer and use it in GitHub Desktop.
PHP Pagination
<?php
/*
$params['total_rows'] = 100;
$params['page'] = isset($_GET['page']) ? $_GET['page'] : 1;
$params['type'] = get_uri_params();
$params['per_page'] = 10;
echo pagination( $params );
*/
function pagination( $params )
{
$per_page = 20;
$type = get_uri_params();
$page = 1;
$jump = 1;
$i = 1;
if (count($params) > 0)
{
foreach ($params as $key => $val)
{
$$key = $val;
}
} else {
return '';
}
$total_page = ( $total_rows % $per_page ) ? floor( $total_rows / $per_page ) + 1 : floor( $total_rows / $per_page );
if ( $page > $total_page ) { $page = $total_page; }
//$prev_page = $page - 1 > 0 ? $page - 1 : 1 ;
//$next_page = $page + 1 >= $total_page ? $total_page : $page + 1;
$next_page = $page + 1;
$prev_page = $page - 1;
$type = !empty($type) ? $type.'&' : '';
$output = "共<strong>$total_rows</strong>条数据,当前第<strong>$page/$total_page</strong>页,每页<strong>$per_page</strong>条数据";
$output .= $page <= 1 ? "<span>首页</span>" : "<a href='?" . $type . "page=1'>首页</a>";
$output .= $prev_page < 1 ? "<span>上一页</span>" : "<a href='?" . $type . "page=$prev_page'>上一页</a>";
$output .= $next_page > $total_page ? "<span>下一页</span>" : "<a href='?" . $type . "page=$next_page'>下一页</a>";
$output .= $page >= $total_page ? "<span>末页</span>" : "<a href='?" . $type . "page=$total_page'>末页</a>";
if ( $jump ) {
$output .= '<span id="jump">转到第<select name="page" id="quick_channel" onchange="gourl()">';
do{
$output .= '<option value="'.$i.'">'.$i.'</option>';
$i++;
}while( $i < $total_page+1 );
$output .= '</select>页</span>';
$output .= '<script type="text/javascript">function gourl(){var x = document.getElementById("quick_channel").value; window.location.href = "http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$type.'page="+x; } document.getElementById("quick_channel").value = '.$page.';</script>';
}
return $output;
}
/**
* 分解页面URI,得到分页参数
*
* @return String
* @author Vince
**/
function get_uri_params( $default = 'page', $uri = array() )
{
$uri = empty($uri) ? $_GET : $uri;
if (is_array($default)) {
foreach ($default as $value) {
unset( $uri[$value] );
}
} else {
unset( $uri[$default] );
}
return http_build_query( $uri );
}
?>
@weishuaiwang
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment