search
HomeBackend DevelopmentPHP TutorialPHP codeigniter framework paging class_PHP tutorial

PHP codeigniter framework paging class_PHP tutorial

Jul 20, 2016 am 11:09 AM
codeigniterphpPaginationexistframeusekind

codeigniter has very easy to use pagination classes. In this tutorial I will do a simple example of returning a set of results from a database tutorial and paginating those results. I will use the latest version of ci. The paging class has not been modified (at least I think not), it is always good to use the latest stable version of the framework
Call method

//Create paging
$config = array();
$this->load->library('hpages');
$config['base_url'] = "channel/lists/c{$slug}/{page}";
$ config['total_rows'] = intval($total);
$config['per_page'] = $pagesize;
$config['uri_segment'] = 1;
$config['num_links'] = 3;
$config['underline_uri_seg'] = 1; //The location of the page number in the underline uri
$this->hpages->init($config);
$this- >template['lists'] = $list;
$this->template['pagestr'] = $this->hpages->create_links(1);

PHP tutorial file code

/**
* file_name: hpages.php
* Haohai network front desk pagination class
*
* @package haohailuo
* @AutHor by Laurence.xu & lt; haohailuo@163.com > * @copyright copyright (c) 2010, haohailuo, inc.
* @link http://www.haohailuo.com
* @since version 1.0 $id$
* @version wed dec 08 12 :21:17 cst 2010
* @filesource
*/
class hpages {

var $base_url = ''; var $per_page                                                                                                                                                                                                                                                                                               due = 2; //Number of left and right links to be displayed
var $cur_page                                                                                                  '; //Home page character
var $next_link '>'; //Characters for the next page
var $last_link                                                                                                                                                                                                                                                                                                    🎜> var $uri_segment                                                                                 Starting html tag
var $full_tag_close = ''; paging area Ending html tag
var $first_tag_open = ''; //HTML tag at the beginning of the homepage
var $first_tag_close = ' '; //HTML tag at the end of the homepage var $last_tag_open = ' '; / /The html tag that starts on the last page
var $last_tag_close = '';                                              ...
var $cur_tag_close = ''; //The end of the current page...
var $next_tag_open                                                                                                                                          .                       = ' ' ; //"Number" The link's opening tag.
var $num_tag_close = ''; //The closing tag of the "number" link.
var $page_query_string = false;
var $query_string_segment = 'per_page';
var $page_mode = 'default' ;             //default for add page at the end? if include {page}, will replace it for current page.
var $underline_uri_seg = -1;                                          ​​​​​​ //Customize the current page number, if this value exists, The system will not automatically determine the current page number, and it will not be enabled by default.

function hpages() {
if (file_exists(apppath.'config/pagination.php')) {
require_once(apppath.'config/pagination.php');
foreach ($config as $key=>$val) {
                                                                                                                             🎜>             
                                                                                       hpages class initialized");
}
 
/**
* Initialization parameters
*
* @see init()
* @author laurence.xu
* @version wed dec 08 12:26:07 cst 2010
* @param $params Parameters to be initialized
*/
function init($params = array()) {
if (count($params) > 0) {
foreach ($params as $key => $ Val) { if (isset ($ this-& gt; $ key)) {
$ this-& gt; $ key = $ value; } /**
* Create paginated links
*
* @see create_links()
* @author laurence.xu
* @version wed dec 08 15:02: 27 cst 2010
                                                                                                          * /
Function Create_links ($ show_info = false, $ top_info = false) {
// If there is no record or 0 number per page, return Empty if ($ this- & gt; total_rows == 0 || $ this- & gt; per_page == 0) {
Return ';
}

// Calculate the total page Number
$num_pages = ceil($this->total_rows / $this->per_page);

                //只有一页,返回空
                if ($num_pages == 1 && !$show_info) {
                        return '';
                }
               
                $ci =& get_instance();

                //获取当前页编号
                if ($ci->config->item('enable_query_strings') === true || $this->page_query_string === true) {
                        if ($ci->input->get($this->query_string_segment) != 0) {
                                $this->cur_page = $ci->input->get($this->query_string_segment);

                                // prep the current page - no funny business!
                                $this->cur_page = (int) $this->cur_page;
                        }
                } else {
                        if (intval($this->custom_cur_page) > 0) {
                                $this->cur_page = (int) $this->custom_cur_page;
                        }else{
                                $uri_segment = $ci->uri->segment($this->uri_segment, 0);
                                if ( !empty($uri_segment) ) {
                                        $this->cur_page = $uri_segment;
                                        //如果有下划线
                                        if ($this->underline_uri_seg >= 0) {
                                                if (strpos($this->cur_page, '-') !== false) {
                                                        $arr = explode('-', $this->cur_page);
                                                }else {
                                                        $arr = explode('_', $this->cur_page);
                                                }
                                                $this->cur_page = $arr[$this->underline_uri_seg];
                                                unset($arr);
                                        }
                                        // prep the current page - no funny business!
                                        $this->cur_page = (int) $this->cur_page;
                                }
                        }
                }
                //echo $this->cur_page;exit;
                //左右显示的页码个数
                $this->num_links = (int)$this->num_links;

                if ($this->num_links                         show_error('your number of links must be a positive number.');
                }

                if ( ! is_numeric($this->cur_page) || $this->cur_page                         $this->cur_page = 1;
                }
               
                //如果当前页数大于总页数,则赋值给当前页数最大值
                if ($this->cur_page > $num_pages) {
                        $this->cur_page = $num_pages;
                }

                $uri_page_number = $this->cur_page;

                if ($ci->config->item('enable_query_strings') === true || $this->page_query_string === true) {
                        $this->base_url = rtrim($this->base_url).'&'.$this->query_string_segment.'=';
                } else {
                        $this->base_url = rtrim($this->base_url, '/') .'/';
                }
               
                if (strpos($this->base_url, "{page}") !== false) {
                        $this->page_mode = 'replace';
                }
               
                $output = $top_output = '';
                //数据总量信息
                if ($show_info) {
                        $output = " 共".$this->total_rows ."条记录 {$this->cur_page}/".$num_pages."页 每页{$this->per_page}条 ";
                }
                //数据信息,显示在上面,以供提醒
                if ($top_info) {
                        $top_output = " 共 ".$this->total_rows ." 条记录 第{$this->cur_page}页/共".$num_pages."页 ";
                }
                //判断是否要显示首页
                if  ($this->cur_page > $this->num_links+1) {
                        $output .= $this->first_tag_open.''.$this->first_link.''.$this->first_tag_close;
                }
               
                //显示上一页
                if  ($this->cur_page != 1) {
                        $j = $this->cur_page - 1;
                        if ($j == 0) $j = '';
                        $output .= $this->prev_tag_open.''.$this->prev_link.''.$this->prev_tag_close;
                }
               
                //显示中间页
                for ($i=1; $i                         if ($i cur_page-$this->num_links || $i > $this->cur_page+$this->num_links) {
                                continue;
                        }
                       
                        //显示中间页数
                        if($this->cur_page == $i){
                                $output .= $this->cur_tag_open.$i.$this->cur_tag_close; //当前页
                        }else {
                                $output .= $this->num_tag_open.''.$i.''.$this->num_tag_close;
                        }
                }
               
                //显示下一页
                if  ($this->cur_page                         $k = $this->cur_page + 1;
                        $output .= $this->next_tag_open.''.$this->next_link.''.$this->next_tag_close;
                }
               
                //显示尾页
                if (($this->cur_page + $this->num_links)                         $output .= $this->last_tag_open.''.$this->last_link.''.$this->last_tag_close;
                }

                $output = preg_replace("#([^:])//+#", "1/", $output);

                // add the wrapper html if exists
                $output = $this->full_tag_open.$output.$this->full_tag_close;

                if ($top_info) {
                        return array($output, $top_output);
                }else {
                        return $output;
                }
        }
       
        /**
* Create link url address
* *
* @param $str
*/
        function makelink($str = '') {
                if($this->page_mode == 'default') {
                        return $this->_forsearch($this->base_url.$str);
                } else {
                        $url = $this->base_url;
                        if ($str == 1) {
                                $url = str_replace('/{page}', '', $this->base_url);
                        }
                        $url = str_replace("{page}", $str, $url);
                       
                        return $this->_forsearch($url);
                }
        }
       
        /**
         * 处理url地址
         *
         * @see                _forsearch()
         * @author        laurence.xu
         * @version        wed dec 08 14:33:58 cst 2010
         * @param        $string pinfo
         * @return       
       */
        function _forsearch($string) {
                $length = strlen($string) - 1;
                if($string{$length} == '/') {
                        $string = rtrim($string, '/');
                }
               
                return site_url($string);
return $string;
}
}

// end pagination class

/* end of file hpages.php */
/* location: ./system/ libraries/hpages.php */


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444803.htmlTechArticlecodeigniter has very easy to use pagination classes. In this tutorial I will do a simple example of returning a set of results from a database tutorial and paginating those results. I will use the latest version of...
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.