PDO 原生处理数据分页

时间:2022-04-25 19:25:19
<?php 
header("content-type:text/html;charset=utf-8");
$pdo = new PDO("mysql:host=127.0.0.1;dbname=demo;charset=utf8",'root','');
$sql = "select * from cai";
$db  = $pdo->query($sql)->fetchAll();
$total = count($db);
$num = 5;
$cpage = isset($_GET['page'])?$_GET['page']:1;
$pagenum = ceil($total/$num);
$offset = ($cpage-1)*$num;
$sql = "select * from cai limit {$offset},{$num}";
$result  = $pdo->query($sql)->fetchAll();
$start = $offset+1;
$end=($cpage==$pagenum)?$total : ($cpage*$num);//结束记录页  
$next=($cpage==$pagenum)? 0:($cpage+1);//下一页  
$prev=($cpage==1)? 0:($cpage-1);//前一页 


?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>展示</title>
</head>
<body>
<center>
<form action="">
<table border="1">
<tr>
<td>ID</td>
<td>标题</td>
<td>作者</td>
<td>时间</td>
<td>分类</td>
<td>操作</td>
</tr>
<?php foreach ($result as $key => $value): ?>
<tr>
<td><?=$value['id']?></td>
<td><?=$value['title']?></td>
<td><?=$value['user']?></td>
<td><?=$value['time']?></td>
<td><?=$value['type']?></td>
<td><a href="javascript:viod(0)">编辑</a>|| <a href="javascript:viod(0)">删除</a></td>
</tr>
<?php endforeach ?>
</table>
</form>
<?php 
echo '<table align="center" width="800" border="1">';   
echo "共<b>$total</b>条记录,本页显示<b>{$start}-{$end}</b> {$cpage}/{$pagenum}";  
    if($cpage==1)  
        echo "  首页  ";  
    else  
        echo "  <a href='?page=1'>首页</a>  ";  
    if($prev)  
        echo "  <a href='?page={$prev}'>上一页</a>  ";  
    else  
        echo "  上一页  ";  
    if($next)  
        echo "  <a href='?page={$next}'>下一页</a>  ";  
    else  
        echo "  下一页  ";  
    if($cpage==$pagenum)  
        echo "  尾页  ";  
    else  
        echo "  <a href='?page={$pagenum}'>尾页</a>  ";  
echo '</td></tr>';  
echo '</table>';  
?>
</center>
</body>

</html>

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

http://www.php.cn/blog/detail/6241.html

https://blog.csdn.net/lisa_miss/article/details/50767569

https://blog.csdn.net/Lisa_Miss/article/details/50770149