很经典的分页程序
Conn.php
header("Content-Type:text/html;charset=utf-8");
$conn = "";
$mysql_localhost = "localhost";
$mysql_user = "root";
$mysql_pws = "sa";
$mysql_data = "page";
/**
* 连接数据库
*/
function OpenDatabase()
{
global $mysql_localhost,$mysql_user,$mysql_pws,$mysql_data; //设置全局变量,但退出函数后值无效
$conn = @mysql_connect($mysql_localhost,$mysql_user,$mysql_pws) or die("提示:数据库连接失败!");
$GLOBALS["conn"] = $conn; //全局变量值,退出函数后值有效
mysql_query("set names 'utf-8'"); //设置编码
$db_selected = mysql_select_db($mysql_data,$conn);
}
/**
* 关闭数据库
*/
function CloseDatabase()
{
mysql_close($GLOBALS["conn"]);
}
?>
Page.php
header("Content-Type:text/html;charset=utf-8");
include("Conn.php");
OpenDatabase(); //打开数据库
//-------调用分页函数-------
$pagenav = _page_list("test",3);
//------------------------
echo $pagenav; //打印出分页返回的字符串
//------------------------显示列表-------------------
$sql = "SELECT * from test limit $firstcount,$pagesize";
$result = mysql_query($sql,$conn); //查询语句
while($row = mysql_fetch_array($result,MYSQL_NUM))
{
echo "
".$row[0]." | ".$row[1]." | ".$row[2];
}
echo "
";
mysql_free_result($result); //释放内存空间
//----------------------------------------------------
echo $pagenav; //打印出分页返回的字符串
//================================================================================
/**
* 函数名:_page_list
* 参数:$table ---- 所要查询的表名
* $page_size ---- 每页的记录数,默认一页显示20条
* 作用:分布显示所有记录
* 使用方法:$pagenav = _page_list("test");
* 然后在要显示分页字符的地方打印出$pagenav
*/
function _page_list($table,$page_size=20)
{
global $firstcount,$pagenav,$page,$conn,$pagesize;
$page = $_GET[page];
$url = _get_url();
$pagesize = $page_size;
$result = mysql_query("select * from $table",$conn);
$total = mysql_num_rows($result); //总记录数
mysql_free_result($result); //释放内存空间
$lastpg = ceil($total / $pagesize); //最后一页,即总页数
$page = min($lastpg,$page); //返回其中最小的数
$prepg = ($page > 1)?$page-1:$page; //上一页
$nextpg = ($page
$firstcount = ($page-1)*$pagesize; //每页第一条记录的指针,默认从0开始
if($firstcount
$pagenav = "共 ".$lastpg." 页 ";
$pagenav .= "
首页";
if($page {
$pagenav .= " 上页";
}
else
{
$pagenav .= "
上页";
}
if($page >= $lastpg)
{
$pagenav .= " 下页";
}
else
{
$pagenav .= "
下页";
}
$pagenav .= "
尾页";
$pagenav .= " 当前第 ".$page." 页";
$pagenav .= "
";
return $pagenav;
}
/**
*函数名:_get_url
*作用:返回页面完整的URL值,即从根目录起,不包含URL最后面的#fragment
*/
function _get_url()
{
global $page;
$url = $_SERVER["REQUEST_URI"]; //获取URL地址
$url_path = parse_url($url,PHP_URL_PATH); //获取文件路径
$url_query = parse_url($url,PHP_URL_QUERY); //获取URL中?号后面的信息,相当于查询字符串
echo $url;