Home Backend Development PHP Tutorial php之分页种代码

php之分页种代码

Jun 13, 2016 am 11:09 AM
gt page parse this url

php之分页类代码

1

/*思路1.把地址栏的URL获取2.分析URL中的query部分--就是?后面传参数的部分3.query部分分析成数组4.把数组中的page单元,+1,-1,形成2个新的数组5.再把新数组拼接成query部分,合成上一页,下一页连接地址*///分页类class Page {   public $total;  //全部条数,从数据库取出   public $prePage = 10; //每页的条数   protected $curr= 1; //默认当前页码    public function __construct($total,$prePage='') {       $this->total = $total; //把总条目信息放在total属性     if ($prePage > 0) {          $this->prePage = $prePage;   //把每页数量放在perPage属性      }       //计算当前页码        if (isset($_GET['page']) && ($_GET['page'] + 0) > 0) {           $this->curr = $_GET['page'] + 0;     }   }   //主体函数  public function showPage() {        if ($this->total <=0) {           return ''; //如果总条目<=0 直接返回空字符串       }       $cnt = ceil($this->total / $this->prePage); //算总页数,进一取整           //根据当前页,算上一页,下一页        /*      分析url,有几种情况?        xx.php      xx.php?id=5     xx.php?page=3       xx.php?id=5&page=3      */              //最终生成的URL里边必然有page=N       $url = $_SERVER['REQUEST_URI'];     $parse = parse_url($url); //把URL分析结果放在数组里       //print_r($parse);      //保证参数里边有page       if (!isset($parse['query'])) {          $parse['query'] = 'page=' .$this->curr;      }       //把query字符串分析成数组,再次确保有page选项        parse_str($parse['query'],$parms);      if (!array_key_exists('page', $parms)) {            $parms['page'] = $this->curr;        }       //上边四种情况都测试一遍,page参数都能生成        //print_r($parms);      //判断除了page之外,还有没有其他参数       if (count($parms) == 1) {           $url = $parse['path'] . '?';        } else {            unset($parms['page']);          $url = $parse['path'] . '?' . http_build_query($parms) . '&';       }       //echo $url     $prev = $this->curr - 1;     $next = $this->curr + 1;     //首页        $indexLink = '<a href="' . $url .'page=' . 1 . '">首页</a>';      //上一页       if ($prev < 1) {         $prevLink = '';     }else {         $prevLink = '<a href="' . $url .'page=' . $prev . '">上一页</a>';      }       //下一页       if ($next > $cnt) {          $nextLink = '';     }else {         $nextLink = '<a href="' . $url .'page=' . $next . '">下一页</a>';      }       //尾页        $lastLink = '<a href="' . $url .'page=' . $cnt . '">尾页</a>';        //echo $indexLink.'  '.$prevLink.'  '.$nextLink .'  '.$lastLink;        //上一页,1 2 3 4 5 下一页     $start = $this->curr - (5-1)/2; //计算左侧开始的页码      $end = $this->curr + (5-1)/2;    //计算右侧开始的页码             //如果左侧的页面,已经小于1,则把小于1 的部分补到右侧       if ($start < 1) {            $end += (1 - $start);           $start = 1; //修改start = 1                   if ($end > $cnt) {               $end  = $cnt;           }       }       //把右侧超出的部分,补到左边     if ($end > $cnt) {           $start -= ($end - $cnt);            $end = $cnt;            if ($start < 1) {                $start = 1;         }       }               //循环出页码数        $pageStr = '';      for ($i=$start; $i <= $end ; $i++) {                             if ($i == $this->curr) {             $pageStr .= $i;             continue;           }           $pageStr .= '<a href="' . $url . 'page=' . $i . '">' . $i . '</a>';     }       return $indexLink.$prevLink.$pageStr.$nextLink.$lastLink;   }}$page = new Page(30,3);echo $page->showPage();

Copy after login

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

PHP function introduction—get_headers(): Get the response header information of the URL PHP function introduction—get_headers(): Get the response header information of the URL Jul 25, 2023 am 09:05 AM

PHP function introduction—get_headers(): Overview of obtaining the response header information of the URL: In PHP development, we often need to obtain the response header information of the web page or remote resource. The PHP function get_headers() can easily obtain the response header information of the target URL and return it in the form of an array. This article will introduce the usage of get_headers() function and provide some related code examples. Usage of get_headers() function: get_header

How to get your Steam ID in a few steps? How to get your Steam ID in a few steps? May 08, 2023 pm 11:43 PM

Nowadays, many Windows users who love games have entered the Steam client and can search, download and play any good games. However, many users' profiles may have the exact same name, making it difficult to find a profile or even link a Steam profile to other third-party accounts or join Steam forums to share content. The profile is assigned a unique 17-digit id, which remains the same and cannot be changed by the user at any time, whereas the username or custom URL can. Regardless, some users don't know their Steamid, and it's important to know this. If you don't know how to find your account's Steamid, don't panic. In this article

Why NameResolutionError(self.host, self, e) from e and how to solve it Why NameResolutionError(self.host, self, e) from e and how to solve it Mar 01, 2024 pm 01:20 PM

The reason for the error is NameResolutionError(self.host,self,e)frome, which is an exception type in the urllib3 library. The reason for this error is that DNS resolution failed, that is, the host name or IP address attempted to be resolved cannot be found. This may be caused by the entered URL address being incorrect or the DNS server being temporarily unavailable. How to solve this error There may be several ways to solve this error: Check whether the entered URL address is correct and make sure it is accessible Make sure the DNS server is available, you can try using the "ping" command on the command line to test whether the DNS server is available Try accessing the website using the IP address instead of the hostname if behind a proxy

How to use URL encoding and decoding in Java How to use URL encoding and decoding in Java May 08, 2023 pm 05:46 PM

Use url to encode and decode the class java.net.URLDecoder.decode(url, decoding format) decoder.decoding method for encoding and decoding. Convert into an ordinary string, URLEncoder.decode(url, encoding format) turns the ordinary string into a string in the specified format packagecom.zixue.springbootmybatis.test;importjava.io.UnsupportedEncodingException;importjava.net.URLDecoder;importjava.net. URLEncoder

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

What is the difference between html and url What is the difference between html and url Mar 06, 2024 pm 03:06 PM

Differences: 1. Different definitions, url is a uniform resource locator, and html is a hypertext markup language; 2. There can be many urls in an html, but only one html page can exist in a url; 3. html refers to is a web page, and url refers to the website address.

Scrapy optimization tips: How to reduce crawling of duplicate URLs and improve efficiency Scrapy optimization tips: How to reduce crawling of duplicate URLs and improve efficiency Jun 22, 2023 pm 01:57 PM

Scrapy is a powerful Python crawler framework that can be used to obtain large amounts of data from the Internet. However, when developing Scrapy, we often encounter the problem of crawling duplicate URLs, which wastes a lot of time and resources and affects efficiency. This article will introduce some Scrapy optimization techniques to reduce the crawling of duplicate URLs and improve the efficiency of Scrapy crawlers. 1. Use the start_urls and allowed_domains attributes in the Scrapy crawler to

See all articles