Home  >  Article  >  Backend Development  >  How to implement paging in php and js

How to implement paging in php and js

PHPz
PHPzOriginal
2023-05-06 19:40:08851browse

With the continuous evolution of web applications and the increase in data volume, paging has become a necessary technical means. The implementation of paging is mainly divided into two methods: server side and client side. In this article, we will focus on how php and js implement paging.

1. Server-side paging

1. Basic principle

Server-side paging depends on the limit and offset settings of the SQL statement. Generally, we first get the total number of records and then calculate the total number of pages. Then, based on the current page number and the number of records displayed on each page, the limit and offset values ​​of the current page are calculated, and the range of records to be obtained is specified in the SQL statement. Finally, the obtained records are returned to the browser for display.

2.php implementation

As a server-side language, php can be used to query data using mysql. The following is a sample code snippet:

<?php
$host = 'localhost';
$username = 'root';
$password = 'password';
$database = 'test';

$conn = new mysqli($host, $username, $password, $database);

if($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}

$per_page = 10; // 每页显示10条记录
$page = isset($_GET['page']) ? $_GET['page'] : 1; // 获取当前页码,默认为第1页
$start = ($page - 1) * $per_page; // 计算当前页的起始记录号

$sql = "SELECT * FROM users LIMIT $start, $per_page";

$result = $conn->query($sql);

if($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
        echo $row['id'] . " " . $row['name'] . "<br>";
    }
}

$conn->close();

echo "<br>";

// 分页导航
echo "<div class='pagination'>";
echo "<a href='?page=1'>第一页</a>";

if($page > 1){
    echo "<a href='?page=".($page-1)."'>上一页</a>";
}

if($page < $total_pages){
    echo "<a href='?page=".($page+1)."'>下一页</a>";
}

echo "<a href='?page=".$total_pages."'>最后一页</a>";
echo "</div>";

The above code implements obtaining user information from the mysql database, displays 10 records per page, and supports paging function. Among them, $per_page represents the number of records displayed on each page, $page represents the current page number, $start represents the starting record number of the current page, and $total_pages represents the total number of pages.

2. Client-side paging

1. Basic principle

Client-side paging refers to obtaining all records from the server to the browser at one time, and then using js for paging deal with. The specific implementation is as follows:

1) Load all data sources into js;

2) Calculate the total number of records and total pages;

3) Based on the current page number and the number of records displayed on each page, to calculate the data range that needs to be displayed on the current page;

4) Render the data and display it on the page;

5) Switch paging by clicking on the page number.

2.js implementation

js implementation of paging is mainly based on jQuery and Bootstrap frameworks. The following is a sample code for paging based on Bootstrap:

<!DOCTYPE html>
<html>
<head>
    <title>客户端分页示例</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <h3>客户端分页示例</h3>
        <table class="table table-bordered table-hover" id="tblData">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>地址</th>
                </tr>
            </thead>
            <tbody id="tblBody">
            </tbody>
        </table>
        <nav>
            <ul class="pagination" id="pagination">
            </ul>
        </nav>
    </div>
    <script>
    $(function(){
        // 模拟数据源
        var data = [
            {id:1, name:"张三", age:20, address:"北京"},
            {id:2, name:"李四", age:22, address:"上海"},
            {id:3, name:"王五", age:25, address:"广州"},
            {id:4, name:"赵六", age:28, address:"深圳"},
            {id:5, name:"周七", age:30, address:"杭州"},
            {id:6, name:"吴八", age:35, address:"南京"},
            {id:7, name:"钱九", age:40, address:"西安"},
            {id:8, name:"孙十", age:45, address:"重庆"},
            {id:9, name:"郑十一", age:50, address:"成都"},
            {id:10, name:"冯十二", age:55, address:"武汉"}
        ];

        var per_page = 5; // 每页显示5条记录
        var total = data.length; // 记录总数
        var total_pages = Math.ceil(total / per_page); // 计算总页数

        // 初始化页码
        for(var i = 1; i <= total_pages; i++){
            var li = "<li><a href='#' onclick='changePage(" + i + ")'>" + i + "</a></li>";
            $("#pagination").append(li);
        }

        // 默认显示第一页
        showData(1);

        // 根据页码显示数据
        function showData(page){
            var start = (page - 1) * per_page;
            var end = start + per_page;
            var html = "";
            for(var i = start; i < end; i++){
                var item = data[i];
                if(item){
                    html += "<tr><td>" + item.id + "</td><td>" + item.name + "</td><td>" + item.age + "</td><td>" + item.address + "</td></tr>";
                }
            }
            $("#tblBody").html(html);
        }

        // 切换页码
        window.changePage = function(page){
            showData(page);
            $("#pagination li").removeClass("active");
            $("#pagination li:nth-child(" + (page+1) + ")").addClass("active");
        }
    });
    </script>
</body>
</html>

The above code demonstrates the use of the Bootstrap framework to implement client-side paging and uses simulated data sources for display.

Conclusion

Both server-side paging and client-side paging have their own advantages and disadvantages. For small-scale data sets, client-side paging can be used to reduce the load on the server. For large-scale data sets, server-side paging is more suitable. Therefore, it is necessary to choose the appropriate paging method according to the actual situation.

The above is the detailed content of How to implement paging in php and js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn