php实现分页代码

mysql+php实现分页

数据库设计,如图

php实现分页代码

<?php

/**

* 1.获取页数

*/

$page = empty($_GET['p'])?1:($_GET['p']);

/**

* 2.处理数据

*/

// 链接数据库

$host = "127.0.0.1";

$user = "root";

$pwd = "root";

$db = "test";

$mysqli = mysqli_connect($host $user $pwd $db);

if (!$mysqli) {

echo "数据库连接错误";

exit();

}

// 设置参数

$pageSize = 10;

// 查询并显示数据(分页公式:(当前页-1)*每页显示的条数 每页显示的条数)

$sql = "select * from page limit ".($page-1)*$pageSize.""."{$pageSize}";

$result = mysqli_query($mysqli $sql);

echo "<table border=1 cellspacing=1 width=30%>";

echo "<tr><td>编号</td><td>姓名</td></tr>";

while ($row = mysqli_fetch_assoc($result)) {

echo "<tr>";

echo "<td>{$row['id']}</td><td>{$row['name']}</td>";

echo "</tr>";

}

echo "</table>";

// 查询总的页数

$total_sql = "select count(*) from page";

$total_result = mysqli_fetch_array(mysqli_query($mysqli$total_sql));

$total = ceil($total_result[0]/$pageSize);

mysqli_close($mysqli);

/**

* 3.输出分页

*/

$showPage =5;// 显示页数

$banner_page = "<div class='page'>";

$pageOffSet = ($showPage-1)/2;//偏移量

if ($page>1) {

$banner_page.= "<a href='".$_SERVER['PHP_SELF']."?p=1'>首页</a>";

$banner_page.= "<a href='".$_SERVER['PHP_SELF']."?p=".($page-1)."'>上一页</a>";

}

// 初始化数据

$start = 1;

$end = $total;

// 数字前的省略(该部分内容顺序不可修改!!!)

if ($total>$showPage) {

if($page>$pageOffSet+1){

$banner_page .= "...";

} if($page>$pageOffSet) {

$start = $page-$pageOffSet;

$end = $total>$page+$pageOffSet?$page+$pageOffSet:$total;

}else{

$start = 1;

$end = $total>$showPage?$showPage:$total;

}if($page+$pageOffSet>$total){

$start = $start-($page+$pageOffSet-$end);

}

}

// 中间省略

for ($i=$start; $i <= $end; $i++) {

$banner_page.= "<a href='".$_SERVER['PHP_SELF']."?p=".($i)."'>{$i}</a>";

}

// 尾部的省略

if ($total>$showPage && $total>($page+$pageOffSet)) {

$banner_page.= "...";

}

if ($page<$total) {

$banner_page.= "<a href='".$_SERVER['PHP_SELF']."?p=".($page+1)."'>下一页</a>";

$banner_page.= "<a href='".$_SERVER['PHP_SELF']."?p={$total}'>尾页</a>";

}

// 自定义跳转页数

$banner_page.="共{$total}页跳转到<form method='get' action='".$_SERVER['PHP_SELF']."'><input type='text' name='p' size='5' />页<input type='submit' value='跳转'/></form></div>";

echo "$banner_page";

?>

相关推荐