美文网首页
PHP分页原理及实现分页案例

PHP分页原理及实现分页案例

作者: 挤时间学习的阿龙 | 来源:发表于2019-05-10 12:31 被阅读0次

    1、PHP分页原理

    image.png

    2、实现上一页和下一页功能,解决上一页越界问题[负数问题]

    (1)关键代码

    注:图片中 改成if($page <=0),否则第1页显示的是第2页


    image.png
    (2)效果
    image.png

    3、解决下一页越界问题

    (1)计算总条数预计
    image.png
    (2)代码
    image.png

    最后放出整个项目代码

    4、全部代码

    <body>
    <?php include ("menu.php"); ?>
    <h3>项目列表</h3>
    <table class="gridtable" width="90%" border="1" cellspacing="0" style="color:#3C3C3C;font-family: 微软雅黑;" >
        <tr>
            <th>ID</th>
            <th width='18%'>项目名称</th>
            <th>城市</th>
            <th>区域</th>
            <th width='18%'>电话</th>
            <th width='18%'>地址</th>
            <th width='15%'>创建时间</th>
            <th width="12%">操作</th>
        </tr>
        <?php
        $num = 5; //每页显示的数量
        $page = isset($_GET['p']) ? $_GET['p'] : 1; //$page如果有get传值就获取,没有就默认第一页
        //页码小于等于1,就不变化
        if ($page <=0){
            $page = $page+1;
        }
        # 计算偏移量
        $offset = ($page-1)*$num;
        # 1.连接数据库
        header("content-type:text/html;charset=utf8");
        $conn = mysqli_connect('127.0.0.1','root','root','office');
        mysqli_set_charset($conn,"utf8");
        # 2.查询数据库
        $sql = "SELECT * FROM `project` LIMIT {$offset}, {$num}";
        if($tempRes=mysqli_query($conn,"SELECT count(*) as count FROM `project`")){
            $row=mysqli_fetch_assoc($tempRes);
            $count = $row['count']; //记录总数
        }
        # 3.循环解析数据
        foreach ($conn->query($sql) as $row){
            echo "<tr>";
            echo "<td>{$row['id']}</td>";
            echo "<td>{$row['name']}</td>";
            echo "<td>{$row['city_id']}</td>";
            echo "<td>{$row['area_id']}</td>";
            echo "<td>{$row['tel']}</td>";
            echo "<td>{$row['address']}</td>";
            echo "<td>{$row['create_time']}</td>";
            echo "<td>
                     <a href='editProject.php?id={$row['id']}'>编辑</a>
                     <a href='javascript:void(0);' onclick='doDel({$row['id']})'>删除</a>
    </td>";
            echo "</tr>";
        }
        //如果到了尾页,就不再往后跳转了
        //计算出总页数= 总记录数 / 每天显示的数量
        $total = ceil($count / $num); //ceil函数大于当前数就显示整数
        if ($page >= $total){
            $page = $page-1;
        }
        echo '<p align="center">';
        echo '<a href="?p='.($page-1).'">上一页</a>';
        for($p=1; $p <= $total; $p++){
            echo '<a href="?p='.$p.'">'.$p.'</a>';
        }
        echo '<a href="?p='.($page+1).'">下一页</a>';
        echo '总数:'.$count;
        echo '总页数:'.$total;
        ?>
    </table>
    </body>
    
    image.png

    待完善:页码很多的情况下,省略

    相关文章

      网友评论

          本文标题:PHP分页原理及实现分页案例

          本文链接:https://www.haomeiwen.com/subject/triooqtx.html