欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP简易分页类

程序员文章站 2022-05-19 23:50:48
...
跳至
_page = $page;
				$this->_totalcount = $totalcount;
				$this->_url = $url;
				$this->_pagesize = $pagesize;	
			} else {
				throw new Exception("构造函数参数不正确~");
			}
		}

		/**
		 * 分页条依赖于bootstrap,格式如下
		 *
  		*		
		*«
		*			1
		*			»
  		*		
		*
		*/
		function page(){
			$page = '';
			$page .= '';
			$page .= "«";
			$b = $this->_page - floor(self::size / 2);
			$e = $this->_page + floor(self::size / 2);
			if($b < 1){
				$b = 1;
				$e = ($this->getTotalPage() < self::size) ? $this->getTotalPage() : self::size;
			}
			if($e > $this->getTotalPage()){
				$b = ($this->getTotalPage() > self::size) ? ($this->getTotalPage() - self::size) : 1;
				$e = $this->getTotalPage();
			}
			for($i = $b; $i _page){
					$page .= '';
				} else {
					$page .= '';
				}
				$page .= "{$i}";
				$page .= '';
			}
			$page .= "»";
			$page .= "";
			$page .= "";
			return $page;
		}

		function limit(){
			return  "limit {$this->getBegin()},{$this->_pagesize}";
		}

		function getBegin(){
			if($this->_page > 0 && $this->_page getTotalPage()){
				return ($this->_page - 1) * $this->_pagesize;
			} else {
				throw new Exception("当前页码不正确~");
			}
		}

		// function getEnd(){
		// 	if($this->_page > 0 && $this->_page getTotalPage()){
		// 		return ($this->_page == $this->getTotalPage()) ? ($this->_totalcount - $this->getBegin()) : ($this->_page * $this->_pagesize);
		// 	} else {
		// 		throw new Exception("当前页码不正确~");
		// 	}
		// }

		function getTotalPage(){
			if($this->_totalcount > 0){
				return ceil($this->_totalcount / $this->_pagesize) ;
			} else {
				throw new Exception("总记录数不正确~");
			}
		}

		private function _getUrl(){
			$url = $this->_url;
			$arr = explode('?', $this->_url);
			if(count($arr) > 1){
				$url = $url . "&";
			} else {
				$url = $url . "?";
			}
			$url = preg_replace("/&?page=[0-9]+/", "", $url);
			return str_replace("?&", "?", $url);
		}

	}


2. [代码]调用

$currentpage = isset($_GET['page']) ? intval($_GET['page']) : 1;
		$mysqli = new mysqli("localhost", "root", "hjj", "php");

		if(mysqli_connect_errno()){
			echo "数据库连接失败";
			exit();
		}

		$mysqli->set_charset("utf8");

		$sql = "select id from message";
		$result = $mysqli->query($sql);

		$page = new Page($currentpage, $result->num_rows, $_SERVER['REQUEST_URI']);

		$result = $mysqli->query("select * from message {$page->limit()}", MYSQLI_USE_RESULT);
		$arr = array();
		while($row = $result->fetch_assoc()){
			$arr[] = $row;
		}

		$smarty->assign("list", $arr);
		$smarty->assign("pagehtml", $page->page());
		$smarty->assign("page", $currentpage);
		$smarty->display("index.tpl");
		$mysqli->close();


相关标签: PHP简易分页类