运行效果
源代码文件
<?php
try{
// pdo连接数据库
$pdo = new pdo("mysql:host=127.0.0.1; dbname=demo", "root", "root");
$pdo->exec("set character set utf8");
}catch(PDOException $e){
echo "连接数据库出错:".$e;
exit();
}
<?php
include("db.php");
// // 批量插入测试数据
// for($i=1; $i<1001; $i++){
// $sql = "insert into articles(title) values('标题".$i."')";
// // echo $sql;
// // break;
// $pdo->exec($sql);
// }
// =======获取总条数===============
// SELECT count(id) as n FROM `articles`
// 预编译sql语句
$stmt = $pdo->prepare("SELECT count(id) as n FROM `articles`");
// 执行sql语句
$stmt->execute();
// 获取返回结果
$res = $stmt->fetch();
$n = $res['n'];
// =======获取总条数===============
// 获取第几页,如果没提供页码,默认第 1 页
$page = isset($_GET['page'])?$_GET['page']:1;
// 预编译sql语句
$stmt = $pdo->prepare("select * from articles limit :offset,:count");
$count = 10;
$offset = ($page-1)*$count; // 根据页码计算出跳过多少行数据
// 绑定参数值
$stmt->bindParam(":offset", $offset, PDO::PARAM_INT);
$stmt->bindParam(":count", $count, PDO::PARAM_INT);
// 执行sql语句
$stmt->execute();
// 获取返回结果
$articles = $stmt->fetchAll();
// var_dump($articles);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<ul>
<?php
foreach($articles as $article){
?>
<li><?=$article['id']?> - <?=$article['title']?></li>
<?php } ?>
</ul>
<div>
<?php
if($page<=1){
?>
<span>上一页</span>
<?php
} else{
?>
<a href="?page=1">第一页</a>
<a href="?page=<?=$page-1?>">上一页</a>
<?php
}
?>
<?php
// 如果大于等于最大页数
if($page>=$n/$count){
?>
<span>下一页</span>
<?php
} else{
?>
<a href="?page=<?=$page+1?>">下一页</a>
<a href="?page=<?=ceil($n/$count)?>">最后一页</a>
<?php
}
?>
<span>当前<?=$page?>/<?=ceil($n/$count)?>页</span>
</div>
</body>
</html>
数据库结构
- 数据库名: demo
- 表名: articles
- 字段
- id int
- title varchar(100)