冰豆网

分享网络精彩
bingdou.com.cn

php实现分页功能

时间:2020-02-20加入收藏

php分页在开发项目中也是经常用到的,下面贴出一小段简单代码,相信您很快就可以掌握了php分页功能的实现以及分页思路。

<?php
//包含连接数据库的公共文件
include_once("./conn.php");
//分页的参数每页显示多少条
$pagesize = 2;
//获取当前页码计算开始行号
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$startrow = ($page-1)*$pagesize; //开始行号
//计算总记录数和计算总页数
$sql = "select * from emails";
$result = mysqli_query($link,$sql);
$records = mysqli_num_rows($result);
//ceil向上取整
$pages = ceil($records/$pagesize);
//构建查询分页的sql语句连等的方式
$sql .=" order by id desc LIMIT {$startrow},{$pagesize}";
$result = mysqli_query($link,$sql);
$arrs = mysqli_fetch_all($result,MYSQLI_ASSOC);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>学生信息管理中心</title>
</head>
<body>
<div style="text-align: center;">
<h2>邮箱预览中心</h2>
<a href="./add.php">添加邮箱</a> 一共有<span style="color: #fe4800"><?php echo $records; ?></span>个邮箱记录
</div>
<table width="600" border="1" align="center" rules="all" cellpadding="5">
<tr>
    <th>编号</th>
    <th>邮箱</th>
    <th>操作</th>
</tr>
<?php
foreach($arrs as $arr){
?>
<tr align="center">
    <td><?php echo $arr['id'] ?></td>
    <td><?php echo $arr['email_id'] ?></td>
    <td><a href="">修改</a> | <a href="./delete.php?id=<?php echo $arr['id'] ?>">删除</a></td>
</tr>
<?php } ?>
<tr>
    <td colspan="9" align="center" height="50">
        <?php
            //循环起点和终点
            $start = $page-5;
            $end = $page+4;
            //如果当前页<=6时
            if($page<=6){
                $start = 1;
                $end = 10;
            }
            //如果$page>=$pages-4
            if($page>=$page-4){
                $start =$page-9;
                $end =$pages;
            }
            //如果$pages<10
            if($page<10){
                $start =1;
                $end =$pages;
            }
            for($i=$start;$i<=$end; $i++){
                //当前页码不加链接
                
                if($page == $i){
                    echo "<span>$i</span>";
                }else{
                    echo "<a href='?page=$i'>$i</a>";
                }
                
            }
        ?>
    </td>
</tr>
</table>
</body>
</html>

数据库连接文件源代码:

<?php
header("Content-type: text/html; charset=utf-8");
$db_host = "localhost";
$db_port = "3306";
$db_user = "root";
$db_pass = "root";
$db_name = "security";
$charset = "utf8";
//var_dump($link);
if(!$link = @mysqli_connect($db_host.":".$db_port,$db_user,$db_pass))
{
    echo "<h2>数据库连接失败</h2>";
    echo "系统错误信息:".mysqli_connect_error();
    die();
}
//echo "选择数据<br>";
if(!mysqli_select_db($link,$db_name))
{
    echo "数据库选择失败";
    die();
}
mysqli_set_charset($link,$charset);

打 赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

TGA: 技巧

分享到:


官方微信二维码冰豆网官方微信公众号