PHP分页
2017-06-28 本文已影响128人
PHPer_
效果图如下:
QQ截图20170628230934.jpg代码如下:
<?php
/**
* Created by PhpStorm.
* User: W&G
* Date: 2017/6/28
* Time: 21:14
*/
/*传入页码*/
$page = $_GET['p'];
/*根据页码取出数据php+mysql*/
$host = 'localhost';
$user = 'root';
$pwd = '123456';
$dbname = 'test';
$page_size = 10;
//连接数据库
$conn = @mysql_connect($host,$user,$pwd) or die();
//检测数据库是否连接成功
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
//选择数据库
mysql_select_db($dbname, $conn) or die('Can\'t use foo : ' . mysql_error());
//设置数据库编码格式
mysql_query('set names utf8');
//准备SQL语句SELECT * FROM 表名 LIMIT 起始位置,显示条数
$sql = "SELECT * FROM tb_admin_menu LIMIT ". ($page-1)*$page_size . ",$page_size";
//向MySQL服务发SQL语句
$result = mysql_query($sql);
//解析处理结果集
echo '<table border="1" cellspacing="0" width="60%">';
echo '<tr><td>id</td><td>name</td></tr>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>'.$row["Fid"].'</td>';
echo '<td>'.$row["Fmenu"].'</td>';
echo '</tr>';
}
echo '</table>';
//释放结果集
mysql_free_result($result);
//获取数据总数
$total_sql = "SELECT COUNT(*) AS total FROM tb_admin_menu";
$total_result = mysql_fetch_assoc(mysql_query($total_sql));
$total = $total_result['total'];
//计算总页数
$total_pages = ceil($total/$page_size);
//关闭数据库连接
mysql_close($conn);
/*显示数据并且显示分页条*/
$page_banner = '';
if ($page > 1) {
$page_banner = '<a href='.$_SERVER['PHP_SELF']."?p=1".'>首页</a>';
$page_banner .= '<a href='.$_SERVER['PHP_SELF']."?p=".($page-1).'>上一页</a>';
}
$page_banner .= '<b>当前第'.$page.'页</b>';
if ($page < $total_pages) {
$page_banner .= '<a href='.$_SERVER['PHP_SELF']."?p=".($page+1).'>下一页</a>';
$page_banner .= '<a href='.$_SERVER['PHP_SELF']."?p=$total_pages".'>尾页</a>';
}
$page_banner .= "共{$total_pages}页<br><br>";
$page_banner .= "<form action='page.php' method='get'>";
$page_banner .= "跳转到第<input type='text' size='2' name='p'>页";
$page_banner .= "<input type='submit' value='确定'>";
$page_banner .= "</form>";
echo $page_banner;