数据库类:
conn.php
<?php
/**
* 数据库操作类
*/
class SQL
{
private $conn;//连接参数
//数据库信息配置
private $config = array(
'host' => '127.0.0.1' ,
'user' => 'root',
'password' => 'root',
'db' => 'demo'
);
//构造方法,自动执行
public function __construct()
{
$this->conn = mysqli_connect($this->config['host'],$this->config['user'],$this->config['password'],$this->config['db']);
mysqli_query($this->conn,'set names utf8');
if (!$this->conn) {
die('链接数据库失败').mysqli_connect_error();
}
}
//数据库发送sql语句
public function query($sql){
return $res=mysqli_query($this->conn,$sql);
}
//显示记录
public function showData($sql)
{
$res = $this->query($sql);
while($rows=mysqli_fetch_assoc($res))
{
$data[] = $rows;//把查出的数据存放到数组里
}
return $data;
}
}
分页类:
function.php
<?php
require 'conn.php';
/**
*分页类
*/
class Page
{
public $pageSize;
public $pageNow;
public $startrow;
public $res;
public $record;
public $pages;
public function fenye($id){
$tool = new SQL();
$this->pageSize=4;//每页显示记录数
$this->records = mysqli_num_rows($tool->query("SELECT id FROM book")); //总记录数
$this->pages = ceil($this->records/$this->pageSize); //总页数
if($id==0||$id<0){
$this->pageNow=1;
$this->startrow = 0;
}else{
$id=$id>$this->pages ? $this->pages:$id;
$this->pageNow=$id;
$this->startrow = ($this->pageNow-1)*$this->pageSize;
}//当前页数
$sql = "SELECT * FROM book LIMIT $this->startrow,$this->pageSize";
//echo $sql;
$this->res=$tool->showData($sql);
//print_r($res);
}
}
首页
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<?php
require 'function.php';
$fenye=new Page();
$id=empty($_GET['id'])?0:$_GET['id'];
// $id=$id<=0?0:$id;
// $id=$id>$fenye->pages?$fenye->pages:$id
$fenye->fenye($id);
$pass=$id-1;
$next=$id+1;
$pass= $pass<1? 1:$pass;
$next = $next>$fenye->pages?$fenye->pages:$next;
echo '<a href="index.php?id='.$pass.'"aria-label="Previous">
<span aria-hidden="true">«</span>
</a></li>';
for($i=1;$i<=$fenye->pages;$i++){
echo '<li><a href="index.php?id='.$i.'">'.$i.'</a></li>';
}
echo'<li>
<a href="index.php?id='.$next.'"aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>';
echo "<pre>";
print_r($fenye->res);
?>
</div>
</body>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</html>
网友评论