search
HomeBackend DevelopmentPHP TutorialWhat is the principle of paging?

What is the principle of paging?

May 31, 2018 am 11:33 AM
Paginationprinciplewhat is

Data paging requires the following conditions:

1. The total number of items participating in paging [$msg_count], this value can be obtained through database query;

2. The number of items displayed on each page [$pagesize], this value is defined by yourself;

3. The number of pages of the current page [$page], this value is transmitted and received through the address bar;

4. The total number of pages [$pagecount] can be calculated from the above information. Here you need to use ceil();

[$pagecount = ceil($msg_count/$pagesize);]

5. Database query uses [limit] in the sql statement to realize data changes:

For example:

select * from table name where condition limit $startnum, $pagesize;

And $startnum = ($page-1)*$pagesize;

Example:

/**
 * 取得上次的过滤条件
 * @param   string  $param_str  参数字符串,由list函数的参数组成
 * @return  如果有,返回array('filter' => $filter, 'sql' => $sql);否则返回false
 */
function get_filter($param_str = '')
{
    $filterfile = basename(PHP_SELF, '.php');//string basename ( string $path [, string $suffix ] )                             返回路径中的文件名部分如果文件名是以 suffix 结束的,那这一部分也会被去掉。 
    if ($param_str)
    {
        $filterfile .= $param_str;
    }
    if (isset($_GET['uselastfilter']) && isset($_COOKIE['ECSCP']['lastfilterfile'])
        && $_COOKIE['ECSCP']['lastfilterfile'] == sprintf('%X', crc32($filterfile)))
    {
        return array(
            'filter' => unserialize(urldecode($_COOKIE['ECSCP']['lastfilter'])),
            'sql'    => base64_decode($_COOKIE['ECSCP']['lastfiltersql'])
        );
    }
    else
    {
        return false;
    }
}
/**
 * 保存过滤条件
 * @param   array   $filter     过滤条件
 * @param   string  $sql        查询语句
 * @param   string  $param_str  参数字符串,由list函数的参数组成
 */
function set_filter($filter, $sql, $param_str = '')
{
    $filterfile = basename(PHP_SELF, '.php');
    if ($param_str)
    {
        $filterfile .= $param_str;
    }
    setcookie('ECSCP[lastfilterfile]', sprintf('%X', crc32($filterfile)), time() + 600);
    setcookie('ECSCP[lastfilter]',     urlencode(serialize($filter)), time() + 600);
    setcookie('ECSCP[lastfiltersql]',  base64_encode($sql), time() + 600);
}
/**
 * 供货商资源管理
 * @param    bool    $is_pagtion
 * @return    array   $arr
 */
function suppliers_resource_manage($is_pagtion=true)
{
    global $db,$ecs;
    $result = get_filter();
    if ($result === false)
    {
        $aiax = isset($_GET['is_ajax']) ? $_GET['is_ajax'] : 0;
        /* 过滤信息 */
        $filter['sort_by'] = empty($_REQUEST['sort_by']) ? 'r.resource_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['resource_id'] = empty($_REQUEST['resource_id'])  ? '' : $_REQUEST['resource_id'];
        $filter['admin_name'] = empty($_REQUEST['admin_name'])  ? '' : trim($_REQUEST['admin_name']);
        $filter['resource_name'] = empty($_REQUEST['resource_name'])  ? '' : trim($_REQUEST['resource_name']);
        $filter['admin_id']  = isset($_REQUEST['admin_id'])?intval($_REQUEST['admin_id']):'-1';
        $filter['resource_type'] = empty($_REQUEST['resource_type']) ? '-1' : intval($_REQUEST['resource_type']);
        $filter['resource_status'] = empty($_REQUEST['resource_status']) ? '-1' : intval($_REQUEST['resource_status']);
        $filter['resource_rank'] = empty($_REQUEST['resource_rank']) ? '-1' : intval($_REQUEST['resource_rank']);
        $filter['resource_key'] = empty($_REQUEST['resource_key'])  ? '' : trim($_REQUEST['resource_key']);
        $filter['menuid'] = 7; 
        $where = 'WHERE 1 ';
        /* 分页大小 */
        $filter[&#39;page&#39;] = empty($_REQUEST[&#39;page&#39;]) || (intval($_REQUEST[&#39;page&#39;]) <= 0) ? 1 : intval($_REQUEST[&#39;page&#39;]);

        if (isset($_REQUEST[&#39;page_size&#39;]) && intval($_REQUEST[&#39;page_size&#39;]) > 0)
        {
            $filter[&#39;page_size&#39;] = intval($_REQUEST[&#39;page_size&#39;]);
        }
        elseif (isset($_COOKIE[&#39;ECSCP&#39;][&#39;page_size&#39;]) && intval($_COOKIE[&#39;ECSCP&#39;][&#39;page_size&#39;]) > 0)
        {
            $filter[&#39;page_size&#39;] = intval($_COOKIE[&#39;ECSCP&#39;][&#39;page_size&#39;]);
        }
        else

        {
            $filter[&#39;page_size&#39;] = 15;
        }
        
        if(!empty($filter[&#39;resource_id&#39;]))
        {
            $resource_id = $filter[&#39;resource_id&#39;] == -1 ? 0 : $filter[&#39;resource_id&#39;];
            $where .= " and r.resource_id=&#39;".$resource_id."&#39;";
        }
        if($filter[&#39;resource_name&#39;]){
            $where .= " AND r.resource_name like &#39;%".mysql_like_quote($filter[&#39;resource_name&#39;])."%&#39; ";
        }
        if($filter[&#39;admin_id&#39;] > -1)
        {
            $where .= " AND r.admin_id = &#39;".$filter[&#39;admin_id&#39;]."&#39; ";
        }
        if ($filter[&#39;resource_type&#39;] > -1) 
        {
            $where .= " AND r.resource_type = &#39;" . $filter[&#39;resource_type&#39;] . "&#39;";
        }
        if ($filter[&#39;resource_status&#39;] > -1) 
        {
            $where .= " AND r.resource_status = &#39;" . $filter[&#39;resource_status&#39;] . "&#39;";
        }
        if ($filter[&#39;resource_rank&#39;] > -1) 
        {
            $where .= " AND r.resource_rank = &#39;" . $filter[&#39;resource_rank&#39;] . "&#39;";
        }
        if($filter[&#39;resource_key&#39;]){
            $where .= " AND r.remark like &#39;%".mysql_like_quote($filter[&#39;resource_key&#39;])."%&#39; ";
        }
        /* 记录总数 */
        $sql = "SELECT COUNT(r.resource_id) FROM " . $ecs->table(&#39;suppliers_resource&#39;)." as r 
                    LEFT JOIN ".$ecs->table(&#39;admin_user&#39;) . " as u
                        ON u.user_id = r.admin_id  " . $where;
        $filter[&#39;record_count&#39;]   = $db->getOne($sql);
        $filter[&#39;page_count&#39;]     = $filter[&#39;record_count&#39;] > 0 ? ceil($filter[&#39;record_count&#39;] / $filter[&#39;page_size&#39;]) : 1;
        /* 查询 */
        $sql = "SELECT r.resource_id, u.user_name as admin_name, r.resource_name, r.resource_link, r.resource_type, r.resource_status, r.resource_rank, r.remark, r.add_time FROM " . $ecs->table(&#39;suppliers_resource&#39;) . " as r 
                    LEFT JOIN " . $ecs->table(&#39;admin_user&#39;) . " as u ON u.user_id = r.admin_id  " . $where;

        $sort_by  = $filter[&#39;sort_by&#39;];
        $sort_order = $filter[&#39;sort_order&#39;];
        $sql .="GROUP BY r.resource_id ORDER BY " . $sort_by . " " . $sort_order;
        if($is_pagtion)
        {
            $sql .=" LIMIT ".($filter[&#39;page&#39;] - 1)*$filter[&#39;page_size&#39;].",".$filter[&#39;page_size&#39;];
        }
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result[&#39;sql&#39;];
        $filter = $result[&#39;filter&#39;];
    }
    $query=$sql;

    $row = $db->getAll($sql);
    /* 格式话数据 */
    foreach ($row AS $key => $value)
    {   
        if ($row[$key][&#39;resource_type&#39;] == 1) {
            $row[$key][&#39;resource_type&#39;] = &#39;中模&#39;;
        }elseif ($row[$key][&#39;resource_type&#39;] == 2) {
            $row[$key][&#39;resource_type&#39;] = &#39;泳装&#39;;
        }elseif ($row[$key][&#39;resource_type&#39;] == 3) {
            $row[$key][&#39;resource_type&#39;] = &#39;阿里&#39;;
        }elseif ($row[$key][&#39;resource_type&#39;] == 2) {
            $row[$key][&#39;resource_type&#39;] = &#39;17网&#39;;
        }
        if ($row[$key][&#39;resource_status&#39;] == 1) {
            $row[$key][&#39;resource_status&#39;] = &#39;已审核&#39;;
        }elseif ($row[$key][&#39;resource_status&#39;] == 2) {
            $row[$key][&#39;resource_status&#39;] = &#39;已弃用&#39;;
        }
        if ($row[$key][&#39;resource_rank&#39;] == 1) 
        {
            $row[$key][&#39;resource_rank&#39;] = &#39;A&#39;;
        }elseif ($row[$key][&#39;resource_rank&#39;] == 2) {
            $row[$key][&#39;resource_rank&#39;] = &#39;B&#39;;
        }elseif ($row[$key][&#39;resource_rank&#39;] == 3) {
            $row[$key][&#39;resource_rank&#39;] = &#39;C&#39;;
        }
        if(strpos($row[$key][&#39;resource_link&#39;], &#39;http://&#39;) === false)
        {
            if (strpos($row[$key][&#39;resource_link&#39;], &#39;https://&#39;) === false) 
            {
                $row[$key][&#39;resource_link&#39;] = substr_replace($row[$key][&#39;resource_link&#39;], &#39;http://&#39;, 0, 0);
            }
        }
    }
    $arr = array(&#39;result&#39; => $row, &#39;filter&#39; => $filter, &#39;page_count&#39; => $filter[&#39;page_count&#39;], &#39;record_count&#39; => $filter[&#39;record_count&#39;],&#39;query&#39;=>$query);
    return $arr;
}

Related recommendations:

Examples of paging principles in php

Detailed explanation of php paging principle

The above is the detailed content of What is the principle of paging?. 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools