博客列表 >学习PHP中的分页原理与代码实现、初识MVC

学习PHP中的分页原理与代码实现、初识MVC

emy
emy原创
2020年05月31日 22:57:51763浏览

一、在项目中分页是十分重要。分页关键词:索引,偏移量,单页显示数量

偏移量 = 每页显示的数量 * (当前页数 - 1)

二、页码代码实现:

1-实现分页条中的直接页码跳转功能

connect.php

<?php
$dsn = 'mysql:host=localhost;dbname=aaa;charset=utf8;port=3306';
$username = 'aaa';
$password = '123456';

try {
    $pdo = new PDO($dsn, $username, $password);
    // 结果集获取方式: 关联
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (Exception $e) {
    die($e->getMessage());
}

handle.php

<?php
// 连接数据库
require 'connect.php';

// 1. 当前的页数/页码
$page = $_GET['p'] ?? 1;

// 2. 每页显示的记录数量
$num = 4;

// 3. 总页数
$sql = "SELECT CEIL(COUNT(`id`)/{$num}) AS `total`  FROM `article`";
$pages = $pdo->query($sql)->fetch()['total'];

// 4. 偏移量
$offset = $num * ($page - 1);

// 5. 分页数据
$sql = "SELECT * FROM `article` LIMIT {$num} OFFSET {$offset}";
$articles = $pdo->query($sql)->fetchAll();

article.php

<?php require 'handle.php' ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分页数据展示</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <table>
    <caption>文章管理系统</caption>
    <thead>

<tr>
    <th>ID</th>
    <th>标题</th>
    <th>关键词</th>
    <th>添加时间</th>
    <th>操作</th>
</tr>
</thead>
<tbody>

<?php foreach ($articles as $article) : ?>
    <tr>
        <td><?php echo $article['id'] ?></td>
        <td><?php echo $article['title'] ?></td>
        <td><?php echo $article['keyword'] ?></td>
        <td><?php echo date('Y / m / d', $article['tjdate']) ?></td>
        <td><button>编辑</button><button>删除</button></td>
    </tr>
   
<?php endforeach; ?>
</tbody>
    </table>
<!-- 添加跳转到首页, 前一页, 下一页, 尾页的功能 -->
    <p>

<!-- 首页 -->
<a href="<?php echo $_SERVER['PHP_SELF'] . '?p=1' ?>">首页</a>

<!-- 前一页 -->
<?php
$prev = $page - 1;
if ($page == 1) $prev = 1; 
?>
<a href="<?php echo $_SERVER['PHP_SELF'] . '?p=' . $prev ?>">前一页</a>


    <?php for ($i=1; $i<=$pages; $i++): ?>
        <?php
        $jump = sprintf('%s?p=%s', $_SERVER['PHP_SELF'],  $i );
        $active = ($i == $page) ? 'active' :null;
        ?>
        <a href="<?php echo $jump ?>" class="<?php echo $active ?>"><?php echo $i ?></a>
    <?php endfor ?>




<!-- 下一页 -->
<?php
$next = $page + 1;
if ($page == $pages) $next = $pages; 
?>
<a href="<?php echo $_SERVER['PHP_SELF'] . '?p=' . $next ?>">下一页</a>

<!-- 尾页 -->
<a href="<?php echo $_SERVER['PHP_SELF'] . '?p='. $pages ?>">尾页</a>


    </p>
</body>
</html>

输出图:

QQ截图20200530224610.jpg

2-实现分页条中的页码省略功能

<?php require 'handle.php' ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分页数据展示</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <table>
    <caption>文章管理系统</caption>
    <thead>

<tr>
    <th>ID</th>
    <th>标题</th>
    <th>关键词</th>
    <th>添加时间</th>
    <th>操作</th>
</tr>
</thead>
<tbody>

<?php foreach ($article as $articlea) : ?>
    <tr>
        <td><?php echo $articlea['id'] ?></td>
        <td><?php echo $articlea['title'] ?></td>
        <td><?php echo $articlea['keyword'] ?></td>
        <td><?php echo date('Y / m / d', $articlea['tjdate']) ?></td>
        <td><button>编辑</button>
<button>删除</button></td>
    </tr>
   
<?php endforeach; ?>
</tbody>
    </table>        <p>
            <?php
            //显示的页码
            $showPages = 5;
            // 起始页
            $startPage = 1;
            // 终止页码
            $endPage = $pages;
            // 偏移量
            $offsetPage = ($showPages - 1) / 2; //2
            if ($showPages < $pages) {
                if ($page > $offsetPage + 1) {
                    $startOmit = '...';
                }
                if ($page > $offsetPage) {
                    $startPage = $page - $offsetPage;
                    $endPage = $page + $offsetPage;
                    if ($endPage > $pages) {
                        $endPage = $pages;
                    }
                } else {
                    $startPage = 1;
                    $endPage = $showPages;
                }
                if ($page + $offsetPage > $pages) {
                    $startPage = $startPage - ($page + $offsetPage - $endPage);
                }
                if ($showPages < $pages && $page + $offsetPage < $pages) {
                    $endOmit = '...';
                }
            }
            ?>
           <?php
            $prev = $page - 1;
            if ($page == 1) $prev = 1;
            ?>
            <a href="<?php echo $_SERVER['PHP_SELF'] . '?p=1' ?> ">首页</a>
            <a href="<?php echo $_SERVER['PHP_SELF'] . '?p=' . $prev ?> ">前一页</a>
            <?php
            if (isset($startOmit)) { ?>
            <a href=""><?php echo $startOmit;  ?></a>
            <?php } ?>
            <?php for ($i = $startPage; $i <= $endPage; $i++) : ?>
            <?php
                $jump = sprintf('%s?p=%s', $_SERVER['PHP_SELF'], $i);
                // echo $jump;
                $active = ($i == $page) ? 'active' : null;
                ?>
            <a href="<?php echo $jump ?>" class="<?php echo $active; ?>"><?php echo $i; ?></a>
            <?php endfor;  ?>
            <?php
            if (isset($endOmit)) { ?>
            <a href=""><?php echo $endOmit;  ?></a>
            <?php } ?>
            <?php
            $next = $page + 1;
            if ($page == $pages) $next = $pages;
            ?>
            <a href="<?php echo $_SERVER['PHP_SELF'] . '?p=' . $next ?> ">下一页</a>
            <a href="<?php echo $_SERVER['PHP_SELF'] . '?p=' . $pages ?> ">尾页</a>
        </p>
</body>
</html>

输出图:每页显示2条记录。

QQ截图20200531213728.jpg

三、学习MVC

1-Model.php模型类

<?php 
namespace mvc_demo;
// 模型类: 用于数据库操作
class Model 
{
    public function getData()
    {
        return (new \PDO('mysql:host=localhost;dbname=aaa', 'aaa','123456'))
        ->query('SELECT * FROM `staffs` LIMIT 10')
        ->fetchAll(\PDO::FETCH_ASSOC);
    }
}

2-View.php 视图

<?php
namespace mvc_demo;

// 视图类
class View
{
    public function fetch($data)
    {
        $table = '<table>';
        $table .= '<caption>员工信息表</caption>';
        $table .= '<tr><th>ID</th><th>姓名</th><th>性别</th><th>职务</th><th>手机号</th><th>入职时间</th></tr>';
        // 将数据循环遍历出来
        foreach ($data as $staff) {
            $table .= '<tr>';
            $table .= '<td>' . $staff['id'] . '</td>';
            $table .= '<td>' . $staff['name'] . '</td>';
            $table .= '<td>' . ($staff['sex'] ? '男' : '女') . '</td>';
            $table .= '<td>' . $staff['position'] . '</td>';
            $table .= '<td>' . $staff['mobile'] . '</td>';
            $table .= '<td>' . date('Y年m月d日', $staff['hiredate']) . '</td>';
            $table .= '</tr>';
        }

        $table .= '</table>';
        return $table;
    }
}
echo '<style>
table {border-collapse: collapse; border: 1px solid;text-align: center; width: 500px;height: 150px;width: 600px;}
caption {font-size: 1.2rem; margin-bottom: 10px;}
tr:first-of-type { background-color:wheat;}
td,th {border: 1px solid; padding:5px}
</style>';

3-第1种依赖注入方式:

<?php
namespace mvc_demo;
// 控制器1
// 1. 加载模型类
require 'Model.php';
// 2. 加载视图
require 'View.php';
// 3. 创建控制
class Controller2
{
    public function index(Model $model, View $view)
    {
        // 1. 获取数据
       $data = $model->getData();

        // 2. 渲染模板/视图
        return $view->fetch($data);
    }

    public function index2(Model $model, View $view)
    {
    }
}
// 客户端
$model = new Model;
$view = new View;
// 实例化控制器类
$controller = new Controller2;
echo $controller->index($model, $view);

// 当前类中对其它类的实例化都在当前类中完成, 造成代码间中的耦合度过高, 过分依赖外部对象
// 使用依赖注入的方式

3-第2种依赖注入方式:

<?php
namespace mvc_demo;
// 控制器依赖注入点改到构造方法, 实现对外部依赖对象的共享
// 1. 加载模型类
require 'Model.php';
// 2. 加载视图
require 'View.php';
// 3. 创建控制
class Controller3
{
    // 依赖对象属性
    private $model;
    private $view;

    // 构造方法
    public function __construct(Model $model, View $view)
    {
        $this->model = $model;
        $this->view = $view;
    }


    public function index()
    {
        // 1. 获取数据
       $data = $this->model->getData();

        // 2. 渲染模板/视图
        return $this->view->fetch($data);
    }
    public function index2()
    {
    // 1. 获取数据
    $data = $this->model->getData();

    // 2. 渲染模板/视图
    return $this->view->fetch($data);
    }
}
// 客户端
$model = new Model;
$view = new View;
// 实例化控制器类
$controller = new Controller3($model, $view);
echo $controller->index();

四、学习总结:

过了一段时间才做分页作业,重温老师的视频,对于分页原理基本清楚,在做编辑功能时,搞了好久,最终还是弄出来了。初步了解MVC知识。感觉现在只能是先照着老师的案例来重写或仿写,在本地调试出来结果。为什么要这样写出来,估计还要多练习。

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议