


A PHP paging class code imitating Aspnetpager with source code download_PHP tutorial
The basic logical idea is the same as that of .net, that is, the configuration through the entity class is replaced by the configuration through the array. The logic is relatively simple, and the paging HTML is spliced based on the conditional judgment.
has the following simple functions:
1: Supports the display or configuration of related buttons
2: Supports the number of pages per page, text name, Free configuration of html tag class name
3: Support url rewritten pages (you need to add rewriting rules in the configuration array yourself)
Easy, just go to the code:
Core code: pager.class.php
class pager{
//Paging parameter configuration
private $config=array(
//Text of home button
"first_btn_text" =>"Home",
//Text of the previous page button,
"pre_btn_text"=>"Previous page",
//Text of the next page
" next_btn_text"=>"Next page",
//Text of the last page,
"last_btn_text"=>"Last page",
//Total number of records* required
"record_count"=>0,
//Page size per page
"pager_size"=>10,
//Current page number*required
"pager_index"=>1,
//The maximum number of buttons displayed on each page
"max_show_page_size"=>10,
//The name of the page number value passed in the browser defaults to page
"querystring_name"=>"page" ,
//Whether URL is rewritten, the default is flase
"enable_urlrewriting"=>false,
//URL rewriting rules such as page/{page} where {page} represents the number of pages
"urlrewrite_pattern"=>"",
//The css name of the paging container
"classname"=>"paginator",
//The class name of the current page button
"current_btn_class"= >"cpb",
//Css of pagination text describing span tag
"span_text_class"=>"stc",
/*Jump detailed text
*totle represents the total number of pages ,
*size represents the number of each page
* goto represents the input box to jump
* record represents the total number of records
* index represents the current page number
*/
" jump_info_text"=>"Total {totle} pages, {size} records per page, jump to {goto} page",
//Jump button text
"jump_btn_text"=>"OK ",
//Whether to show the jump
"show_jump"=>false,
//Whether to show the previous button homepage & previous page
"show_front_btn"=>true,
//Whether to display the following button next page & last page
"show_last_btn"=>true
);
/*
* Constructor of class
* $config: this Configuration of paging class
*/
public function __construct($config)
{
$this->init_config($config);
}
function __destruct()
{
unset($this->config);
}
/*
* Construct the main paging function
*/
public function builder_pager()
{
//Paging string
$pager_arr=array();
//Size of each page
$pager_size=$this->config["pager_size"];
// Get the total number of paging
$pager_num=$this->config["record_count"]%$pager_size==0?$this->config["record_count"]/$pager_size:floor($this-> ;config["record_count"]/$pager_size)+1;
//If the current page number is 0, set it to 1
$pager_index=round($this->config["pager_index"] )==0?1:round($this->config["pager_index"]);
//If the current page number is greater than or equal to the last page, the current page number is set to the last page
$ pager_index=$pager_index>=$pager_num?$pager_num:$pager_index;
//The page number of the next page
$pager_next=$pager_index>=$pager_num?$pager_num:($pager_index+1);
//Get the url that needs to be redirected
$url=$this->get_url();
//Add the div at the beginning
$classname=$this->config["classname"] ;
$pager_arr[]="
//Add the html of the first two buttons
if($this->config["show_front_btn "])
{
//If the current page number is 1, the two front buttons will be disabled
$attr=$pager_index==1?"disabled=disabled":"";
$pager_arr[]=$this->get_a_html(self::format_url($url,1),$this->config["first_btn_text"],$attr);
$pager_arr[]=$ this->get_a_html(self::format_url($url,$pager_index-1),$this->config["pre_btn_text"],$attr);
}
//The starting point of the currently displayed page number Start 1~10 1 11~20 11
$current_pager_start=$pager_index%$pager_size==0?($pager_index/$pager_size-1)*$pager_size+1:floor($pager_index/$pager_size)*$pager_size +1;
//The end of the currently displayed page number
$current_pager_end=($current_pager_start+$pager_size-1)>=$pager_num?$pager_num:($current_pager_start+$pager_size-1);
// Add html that jumps to the previous level
if($pager_index>$pager_size)
{
$pager_arr[]=$this->get_a_html(self::format_url($url,$current_pager_start- 1),"...");
}
//Main page number part
for($i=$current_pager_start;$i<=$current_pager_end;$i++)
{
if($i!=$pager_index)
{
$pager_arr[]=$this->get_a_html(self::format_url($url,$i),$i);
}else{
//If this is the current page
$pager_arr[]=$this->get_span_html($i,$this->config["current_btn_class"]);
}
}
//Add the next layer of html
if($pager_index<=($pager_num-$pager_num%$pager_size))
{
$pager_arr[]=$this->get_a_html(self ::format_url($url,$current_pager_end+1),"...");
}
//添加后面两个按钮的html
if($this->config["show_last_btn"])
{
//如果当前的页码为最后一页 则last这两个按钮则会被禁用
$attr=$pager_index>=$pager_num?"disabled=disabled":"";
$pager_arr[]=$this->get_a_html(self::format_url($url,$pager_next),$this->config["next_btn_text"],$attr);
$pager_arr[]=$this->get_a_html(self::format_url($url,$pager_num),$this->config["last_btn_text"],$attr);
}
//添加跳转的html
if($this->config["show_jump"])
{
$patterns=array("/\{totle\}/","/\{size\}/","/\{goto\}/","/\{record\}/","/\{index\}/",);
$replacements=array(
$pager_num,
$pager_size,
"\n",
$this->config["record_count"],
$this->config["pager_index"]
);
//替换特定的标签组成跳转
$pager_arr[]=preg_replace($patterns,$replacements,$this->config["jump_info_text"]);
$btn_text=$this->config['jump_btn_text'];
$pager_arr[]="".$this->config['jump_btn_text']."\n";
$pager_arr[]=$this->get_jumpscript($url);
}
$pager_arr[]="
$this->config["pager_index"]=$pager_index;
return implode($pager_arr);
}
/*
* Get the url that needs to be processed, Support rewriting configuration, url of various parameters
*/
private function get_url()
{
//If set to allow url rewriting
if($this->config ["enable_urlrewriting"])
{
//Get the url where the calling file is located
$file_path="http://".$_SERVER["HTTP_HOST"].$_SERVER["PHP_SELF"];
//Get the network directory where the calling url is located
$file_path=substr($file_path,0,strripos($file_path,"/"))."/";
//Append the directory directly Write rules to form a new url
$url=$file_path.$this->config["urlrewrite_pattern"];
}else{
//Get the absolute url of the current calling page
$url ="http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
//The name of the paging parameter passed in the browser
$querystring_name=$this->config ['querystring_name'];
//If the url contains the string of php?, you need to replace the paging parameters
if(strpos($url,"php?"))
{
//If the words page=xxx exist
$pattern="/$querystring_name=[0-9]*/";
if(preg_match($pattern,$url))
{
//Replace the numbers in the words containing page=*** with {0}
$url=preg_replace($pattern,"$querystring_name={page}",$url);
}else{
$url.="&$querystring_name={page}";
}
}else{
//Add parameters directly to form the complete url for paging
$url.="?$querystring_name ={page}";
}
}
return $url;
}
/*
* Get the html of the a tag
*$url: the direction to which the a tag is directed html
*$title: The title of the a tag
**$attr: The additional attributes on the a tag do not need to be written
*/
private static function get_a_html($url,$title,$ attr="")
{
return "$titlen";
}
/*
* Get the html of the span tag
* $num: The text in span, that is, the page number
* $classname: The class name of the span tag
*/
private static function get_span_html($num,$classname)
{
return "$numn";
}
/*
* Format url
* $url original url
* $page page number
*/
private static function format_url($url,$page)
{
return preg_replace("/{page}$/",$page,$url);
}
/*
*Initialize the paging configuration file
*If the key value is not included in the parameter , the declared value is used by default
*/
private function init_config($config)
{
//Determine whether the value exists, is an array, and contains records
if(isset ($config)&&is_array($config)&&count($config)>0){
foreach($config as $key=>$val)
{
$this->config[$ key]=$val;
}
}
}
/*
* Method to construct a jump function script
*$url: the url that needs to be jumped
*/
private function get_jumpscript($url)
{
$scriptstr = "n";
return $scriptstr;
}
/*
* Construct a function in php similar to the format method in .net
* Usage: format("hello,{0},{1},{2}", 'x0','x1 ','x2')
*/
private function format() {
$args = func_get_args();
if (count($args) == 0) { return;}
if (count($args) == 1) { return $args[0]; }
$str = array_shift($args);
$str = preg_replace_callback('/\{(0|[1 -9]\d*)\}/', create_function('$match', '$args = '.var_export($args, true).'; return isset($args[$match[1]]) ? $ args[$match[1]] : $match[0];'), $str);
return $str;
}
}
?>
Directly call
php
$config1=array(
"record_count"=>703,
"pager_size"=>10,
"show_jump"=>true,
"pager_index"=> ;$_GET["page"]
);
$pager_simple=new pager($config1);
echo $pager_simple->builder_pager();
?>
Finally, let’s take a look at the demo pictures:

Since I have just learned PHP recently, please let me know if there are any irregularities, inefficiencies, redundancies or design issues in the code. Please give me your advice.
demo source code download

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.
