search
HomeBackend DevelopmentPHP TutorialShare: An example code of PHP page turning (paging) class

  1. /**
  2. * filename: ext_page.class.php
  3. * @package:phpbean
  4. * descrīption: Super powerful paging class, four paging modes, the default paging style is similar to Baidu and Google.
  5. * 2.0 added functions: supports custom styles, custom styles, supports both PHP4 and PHP5,
  6. * example:
  7. * Four paging modes:
  8. require_once('../libs/classes/page.class.php' );
  9. $page=new page(array('total'=>1000,'perpage'=>20));
  10. echo 'mode:1
    '.$page->show();
  11. echo '
    mode:2
    '.$page->show(2);
  12. echo '
    mode:3
    '.$page->show(3);
  13. echo '
    mode:4
    '.$page->show(4);
  14. Turn on AJAX:
  15. $ajaxpage=new page(array('total'=>1000,'perpage'=> ;20,'ajax'=>'ajax_page','page_name'=>'test'));
  16. echo 'mode:1
    '.$ajaxpage->show();
  17. Use inheritance customization Pagination display mode.
  18. Editing: Scripting School http://bbs.it-home.org
  19. */
  20. class _page
  21. {
  22. /**
  23. * config ,public
  24. */
  25. var $page_name="PB_page";//page tag, used to control url Page. For example, PB_page in xxx.php?PB_page=2
  26. var $next_page='>';//Next page
  27. var $pre_page=' var $first_page='First' ;//Homepage
  28. var $last_page='Last';//Last page
  29. var $pre_bar=' var $next_bar='>>';//Next A paging bar
  30. var $format_left='[';
  31. var $format_right=']';
  32. var $is_ajax=false;//Whether AJAX paging mode is supported
  33. /**
  34. * private
  35. *
  36. */
  37. var $pagebarnum= 10;//Control the number of record strips.
  38. var $totalpage=0;//Total number of pages
  39. var $ajax_action_name='';//AJAX action name
  40. var $nowindex=1;//Current page
  41. var $url="";//url address header
  42. var $offset=0;
  43. /**
  44. * constructor构造函数
  45. *
  46. * @param array $array['total'],$array['perpage'],$array['nowindex'],$array['url'],$array['ajax']...
  47. */
  48. function page($array)
  49. {
  50. if(is_array($array)){
  51. if(!array_key_exists('total',$array))$ this->error(__FUNCTION__,'need a param of total');
  52. $total=intval($array['total']);
  53. $perpage=(array_key_exists('perpage',$array))?intval( $array['perpage']):10;
  54. $nowindex=(array_key_exists('nowindex',$array))?intval($array['nowindex']):'';
  55. $url=(array_key_exists('url ',$array))?$array['url']:'';
  56. }else{
  57. $total=$array;
  58. $perpage=10;
  59. $nowindex='';
  60. $url='';
  61. }
  62. if((!is_int($total))||($totalerror(__FUNCTION__,$total.' is not a positive integer!');
  63. if((!is_int( $perpage))||($perpageerror(__FUNCTION__,$perpage.' is not a positive integer!');
  64. if(!empty($array['page_name']) )$this->set('page_name',$array['page_name']);//Set pagename
  65. $this->_set_nowindex($nowindex);//Set the current page
  66. $this->_set_url( $url);//Set the link address
  67. $this->totalpage=ceil($total/$perpage);
  68. $this->offset=($this->nowindex-1)*$perpage;
  69. if (!empty($array['ajax']))$this->open_ajax($array['ajax']);//Open AJAX mode
  70. }
  71. /**
  72. * Set the value of the specified variable name in the class. If the change does not belong to this class, an exception will be thrown
  73. *
  74. * @param string $var
  75. * @param string $value
  76. */
  77. function set($ var,$value)
  78. {
  79. if(in_array($var,get_object_vars($this)))
  80. $this->$var=$value;
  81. else {
  82. $this->error(__FUNCTION__,$var. " does not belong to PB_Page!");
  83. }
  84. }
  85. /**
  86. * Turn on reverse AJAX mode
  87. *
  88. * @param string $action Default ajax triggered action.
  89. */
  90. function open_ajax($action)
  91. {
  92. $this->is_ajax=true;
  93. $this->ajax_action_name=$action;
  94. }
  95. /**
  96. * Get the code to display "next page"
  97. *
  98. * @param string $style
  99. * @return string
  100. */
  101. function next_page($style='')
  102. {
  103. if($this->nowindextotalpage){
  104. return $this->_get_link($this->_get_url($this->nowindex+1),$this->next_page,$style);
  105. }
  106. return ''.$this->next_page.'';
  107. }
  108. /**
  109. * Get the code to display "previous page"
  110. *
  111. * @param string $style
  112. * @return string
  113. */
  114. function pre_page($style='')
  115. {
  116. if($this->nowindex>1){
  117. return $this->_get_link($this->_get_url($this->nowindex-1),$this->pre_page,$style);
  118. }
  119. return ''.$this->pre_page.'';
  120. }
  121. /**
  122. * Get the code to display "Home Page"
  123. *
  124. * @return string
  125. */
  126. function first_page($style='')
  127. {
  128. if($this->nowindex==1){
  129. return ''.$this->first_page.'';
  130. }
  131. return $this->_get_link($this->_get_url(1),$this->first_page,$style);
  132. }
  133. /**
  134. * Get the code to display the "last page"
  135. *
  136. * @return string
  137. */
  138. function last_page($style='')
  139. {
  140. if($this->nowindex==$this->totalpage){
  141. return ''.$this->last_page.'';
  142. }
  143. return $this->_get_link($this->_get_url($this->totalpage),$this->last_page,$style);
  144. }
  145. function nowbar($style='',$nowindex_style='')
  146. {
  147. $plus=ceil($this->pagebarnum/2);
  148. if($this->pagebarnum-$plus+$this->nowindex>$this->totalpage)$plus=($this->pagebarnum-$this->totalpage+$this->nowindex);
  149. $begin=$this->nowindex-$plus+1;
  150. $begin=($begin>=1)?$begin:1;
  151. $return='';
  152. for($i=$begin;$ipagebarnum;$i++)
  153. {
  154. if($itotalpage){
  155. if($i!=$this->nowindex)
  156. $return.=$this->_get_text($this->_get_link($this->_get_url($i),$i,$style));
  157. else
  158. $return.=$this->_get_text(''.$i.'');
  159. }else{
  160. break;
  161. }
  162. $return.="n";
  163. }
  164. unset($begin);
  165. return $return;
  166. }
  167. /**
  168. * Get the code to display the jump button
  169. *
  170. * @return string
  171. */
  172. function select()
  173. {
  174. $return='';
  175. return $return;
  176. }
  177. /**
  178. * Get the value required for limit in the mysql statement
  179. *
  180. * @return string
  181. */
  182. function offset()
  183. {
  184. return $this->offset;
  185. }
  186. /**
  187. * Control paging display style (you can add corresponding style)
  188. *
  189. * @param int $mode
  190. * @return string
  191. */
  192. function show($mode=1)
  193. {
  194. switch ($mode)
  195. {
  196. case '1':
  197. $this->next_page='下一页';
  198. $this->pre_page='上一页';
  199. return $this->pre_page().$this->nowbar().$this->next_page().'第'.$this->select().'页';
  200. break;
  201. case '2':
  202. $this->next_page='下一页';
  203. $this->pre_page='上一页';
  204. $this->first_page='首页';
  205. $this->last_page='尾页';
  206. return $this->first_page().$this->pre_page().'[第'.$this->nowindex.'页]'.$this->next_page().$this->last_page().'第'.$this->select().'页';
  207. break;
  208. case '3':
  209. $this->next_page='下一页';
  210. $this->pre_page='上一页';
  211. $this->first_page='首页';
  212. $this->last_page='尾页';
  213. return $this->first_page().$this->pre_page().$this->next_page().$this->last_page();
  214. break;
  215. case '4':
  216. $this->next_page='下一页';
  217. $this->pre_page='上一页';
  218. return $this->pre_page().$this->nowbar().$this->next_page();
  219. break;
  220. case '5':
  221. return $this->pre_bar().$this->pre_page().$this->nowbar().$this->next_page().$this->next_bar();
  222. break;
  223. case '6':
  224. return $this->select();
  225. break;
  226. case '7':
  227. return $this->nowbar();
  228. break;
  229. }
  230. }
  231. /*----------------private function (私有方法)-----------------------------------------------------------*/
  232. /**
  233. * Set url header address
  234. * @param: String $url
  235. * @return boolean
  236. */
  237. function _set_url($url="")
  238. {
  239. if(!empty($url)){
  240. //手动设置
  241. $this->url=$url.((stristr($url,'?'))?'&':'?').$this->page_name."=";
  242. }else{
  243. //自动获取
  244. if(empty($_SERVER['QUERY_STRING'])){
  245. //不存在QUERY_STRING时
  246. $this->url=$_SERVER['REQUEST_URI']."?".$this->page_name."=";
  247. }else{
  248. //
  249. if(stristr($_SERVER['QUERY_STRING'],$this->page_name.'=')){
  250. //地址存在页面参数
  251. $this->url=str_replace($this->page_name.'='.$this->nowindex,'',$_SERVER['REQUEST_URI']);
  252. $last=$this->url[strlen($this->url)-1];
  253. if($last=='?'||$last=='&'){
  254. $this->url.=$this->page_name."=";
  255. }else{
  256. $this->url.='&'.$this->page_name."=";
  257. }
  258. }else{
  259. //
  260. $this->url=$_SERVER['REQUEST_URI'].'&'.$this->page_name.'=';
  261. }//end if
  262. }//end if
  263. }//end if
  264. }
  265. /**
  266. * Set current page
  267. *
  268. */
  269. function _set_nowindex($nowindex)
  270. {
  271. if(empty($nowindex)){
  272. //系统获取
  273. if(isset($_GET[$this->page_name])){
  274. $this->nowindex=intval($_GET[$this->page_name]);
  275. }
  276. if(isset($_POST['PB_Page_Select'])){
  277. $this->nowindex=$_POST['PB_Page_Select'];
  278. }
  279. }else{
  280. //手动设置
  281. $this->nowindex=intval($nowindex);
  282. }
  283. }
  284. /**
  285. * Return the address value for the specified page
  286. *
  287. * @param int $pageno
  288. * @return string $url
  289. */
  290. function _get_url($pageno=1)
  291. {
  292. return $this->url.$pageno;
  293. }
  294. /**
  295. * Get pagination display text, for example, by default _get_text('1') will return [1]
  296. *
  297. * @param String $str
  298. * @return string $url
  299. */
  300. function _get_text($str)
  301. {
  302. return $this->format_left.$str.$this->format_right;
  303. }
  304. /**
  305. * Get link address
  306. */
  307. function _get_link($url,$text,$style=''){
  308. $style=(empty($style))?'':'class="'.$style.'"';
  309. if($this->is_ajax){
  310. //如果是使用AJAX模式
  311. return ''.$text.'';
  312. }else{
  313. return ''.$text.'';
  314. }
  315. }
  316. /**
  317. * Error handling method
  318. */
  319. function error($function,$errormsg)
  320. {
  321. die('Error in file '.__FILE__.' ,Function '. $function.'() :'.$errormsg);
  322. }
  323. }
  324. // Inherit the paging class and add database access capabilities.
  325. class Page extends _Page {
  326. var $db; //db connected object
  327. var $_Sql_Query = ''; //Query the sql of the database
  328. var $_Total = 0; //The total records queried. Must first be
  329. var $_Rst = array(); //The records queried.
  330. / **
  331. * Paging query library.
  332. *
  333. * @param String $Sql Record query SQL statement.
  334. * @param int $pagenuber How many records per page.
  335. * @param int $pagen Current page.
  336. * @param String $url Parameters brought into the paging link. index.php?xx=b&bb=33
  337. * @param String $pname The mark of the current page. The default is index.php?xx=b&bb=33&page=2 if there are special requirements
  338. You can modify the parameters of $pname. For example: $pname='db_page', it becomes: index.php?xx=b&bb=33&db_page=2
  339. * @return Mysql_Page
  340. */
  341. function Page($db, $sql_query = '', $max_rows_per_page = 20, $current_page_number = 0, $url = '', $parameters = '', $pname = 'PB_page', $otc = '*') {
  342. $this -> db = $db;
  343. $pos_to = strlen($sql_query);
  344. $pos_from = strpos($sql_query, ' from', 0);
  345. $pos_group_by = strpos ($sql_query, ' group by', $pos_from);
  346. if (($pos_group_by $pos_having = strpos($sql_query, ' having ', $pos_from);
  347. if (($pos_having $pos_order_by = strpos($sql_query, ' order by', $pos_from);
  348. if (($pos_order_by $reviews_count = $this -> db -> getResults("select count($otc) as total " . substr($sql_query, $pos_from, ($pos_to - $pos_from)));
  349. $query_num_rows = $reviews_count[0]['total'];
  350. $this -> _Total = $query_num_rows;
  351. $num_pages = ceil($query_num_rows / $max_rows_per_page);
  352. if ($current_page_number > $num_pages) {
  353. $current_page_number = $num_pages;
  354. }
  355. $offset = ($max_rows_per_page * ($current_page_number - 1));
  356. if ($offset if ($offset > 0) {
  357. $offset = $offset + 1;
  358. }
  359. $this -> _Sql_Query = $sql_query . " limit " . $offset . ", " . $max_rows_per_page;
  360. $this -> setData(); //Query the database.
  361. parent :: page(array('total' => $query_num_rows, 'perpage' => $max_rows_per_page, 'page_name' = > $pname, 'url' => $url, 'parameters' => $parameters));
  362. }
  363. /**
  364. * Get the records of the current page and return an array.
  365. */
  366. function findByAll() {
  367. return $this -> _Rst;
  368. }
  369. /**
  370. * Display paging information.
  371. *
  372. * @param int $model
  373. */
  374. function dispaly_links($model) {
  375. $this -> show($model);
  376. }
  377. /**
  378. * Returns the number of records.
  379. *
  380. * @return Int
  381. */
  382. function getCount() {
  383. return $this -> _Total;
  384. }
  385. /**
  386. * Get the number of query result records..
  387. *
  388. * @return Int
  389. */
  390. function getRows() {
  391. return count($this -> _Rst);
  392. }
  393. /**
  394. * Execute query function.
  395. * Calculate array.
  396. * Private method.
  397. */
  398. function setData() {
  399. $this -> _Rst = $this -> db -> getResults($this -> _Sql_Query);
  400. }
  401. }
  402. ?>
Copy code


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: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

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.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

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

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool