您的位置:首页 > 其它

数据分页显示的简单实现

2017-04-20 23:45 253 查看
说明:

分页显示是通过SQL语句中的limit来实现,下面是我对分页进行简单的封装

define("HOST",'localhost');
define("USERNAME",'root');
define("PWD",'');
define("DB_NAME",'');
define("CHARSET",'UTF8');
class Page
{
private $link;//数据库连接
private $pages;//数据显示所需总页数
private $num;//每页显示数据条数

function __construct($num){//连接数据库
$this->num=$num;
$link = mysqli_connect(HOST,USERNAME,PWD);
if(!$link){
exit('连接失败,errno:'.mysqli_connect_errno().' error:'.mysqli_connect_error());
}
if(!mysqli_select_db($link,DB_NAME)){
exit('数据库指定失败,errno:'.mysqli_errno($link).' error:'.mysqli_error($link));
}
if(!mysqli_set_charset($link,CHARSET)){
exit('字符集设置失败,errno:'.mysqli_errno($link).' error:'.mysqli_error($link));
}
$sql = 'select id from user';
$res = mysqli_query($link,$sql);
$this->pages = ceil(mysqli_num_rows($res)/$this->num);//求出所需页数
mysqli_free_result($res);
$this->link=$link;
}

function showPages(){//显示页码
$p=1;//第几页
echo '<a href="?p=1">首页</a>  ';
while($p<=$this->pages){
echo '<a href="?p='. $p .'">'. $p .'</a>  ';
$p++;
}
echo '<a href="?p='. $this->pages .'">尾页</a>  ';
}
function getPage(){
if(empty($_GET['p'])){//因为首次进入本页面不存在p的值,因此需要指定p的值,默认为第一页
$_GET['p']=1;
$p=$_GET['p'];
}else{
$p=$_GET['p'];
}
return $p;
}
function showTable($sql='select * from user'){//显示数据,可以自己定义sql语句
$p=$this->getPage();
echo '<table border="1" width="800" align="center">';
$sql = $sql.' limit '.($p-1)*$this->num .','. $this->num;
$result = mysqli_query($this->link,$sql);
if($result && mysqli_num_rows($result)){
$flag=true;
while($row  = mysqli_fetch_assoc($result)){
if($flag){//显示字段名字
echo '<tr>';
foreach($row as $key=>$val){
echo '<th>'.$key.'</th>';
}
echo '</tr>';
$flag=false;
}
echo '<tr>';
foreach($row as $val){//输出具体数据
echo '<td>'.$val.'</td>';
}
echo '</tr>';
}
echo '</table>';
}else{
echo 'sql执行错误,请检查你的sql语句 '.$sql;
}
mysqli_free_result($result);
}

function __destruct(){
mysqli_close($this->link);
}
}

/*测试*/

$page = new Page(8);//表示每页显示8条数据
$sql = 'select username,email,reg_time from user';
$page->showTable($sql);

$page->showPages();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: