今天為大家獻(xiàn)上一段代碼,這是一段php分頁(yè)代碼:
<?php
//創(chuàng)建分頁(yè)類
class Page {
private $_all_num; //數(shù)據(jù)總個(gè)數(shù)
private $_page_size; //每頁(yè)顯示幾條數(shù)據(jù)
private $_page; //當(dāng)前頁(yè)面
private $_all_page; //總頁(yè)碼
private $_url; //頁(yè)面地址
private $_limit; //數(shù)據(jù)庫(kù)查詢語(yǔ)句
private $_sign; //地址符號(hào)
//攔截器
public function __get($_key) {
return $this->$_key;
}
public function __construct($_all_num,$_page_size) {
$this->_all_num = $_all_num;
$this->_page_size = $_page_size;
$this->_all_page = ceil($this->_all_num / $this->_page_size);
$this->_page = $this->setPage();
$this->_url = $this->setUrl();
$this->_limit = 'LIMIT '.($this->_page * $this->_page_size - $this->_page_size).','.$this->_page_size;
}
//獲取當(dāng)前頁(yè)碼
private function setPage() {
if (!empty($_GET['page']) && $_GET['page'] > 0) {
if ($_GET['page'] <= $this->_all_page) {
return ceil($_GET['page']);
} else {
return $this->_all_page;
}
} else {
return 1;
}
}
//獲取地址
private function setUrl() {
$_url = $_SERVER['REQUEST_URI'];
if (!empty($_url)) {
$_par_url = parse_url($_url);
if (isset($_par_url['query'])) {
parse_str($_par_url['query'],$_arr);
if (isset($_arr['page'])) {
unset($_arr['page']);
}
if (!empty($_arr)) {
$_http = http_build_query($_arr);
$_end_url = $_par_url['path'] . '?' . $_http;
$this->_sign = '&';
} else {
$_end_url = $_par_url['path'];
$this->_sign = '?';
}
} else {
$_end_url = $_par_url['path'];
$this->_sign = '?';
}
}
return $_end_url;
}
//顯示分頁(yè)
public function numPage() {
$_num = '';
//前面
for ($i=1; $i<$this->_page; $i++) {
if ($i<1) continue;
$_num .= "<a href='".$this->_url. $this->_sign ."page=".$i."'>".$i."</a>";
}
//自己
$_num .= "<a class='me' href='".$this->_url. $this->_sign ."page=".$this->_page."'>".$this->_page."</a>";
//后面
for ($i=$this->_page+1; $i<=$this->_all_page; $i++) {
if ($i>$this->_all_page) continue;
$_num .= "<a href='".$this->_url. $this->_sign ."page=".$i."'>".$i."</a>";
}
return $_num;
}
}
?>
大家可以將上面一段代碼復(fù)制到文本編輯器中這樣看的會(huì)舒服一點(diǎn)!下面講一下具體步驟:
1、創(chuàng)建一個(gè)分頁(yè)類:class Page {};
2、獲取需要顯示數(shù)據(jù)的個(gè)數(shù),并且記錄在Page類中,這里數(shù)據(jù)的個(gè)數(shù)通過(guò)數(shù)據(jù)去獲取就不詳細(xì)說(shuō)了!然后設(shè)置每頁(yè)顯示數(shù)據(jù)的條數(shù)!
3、獲取當(dāng)前頁(yè)面地址!
這段代碼大概意思就是當(dāng)你的地址跟著?時(shí),那么點(diǎn)擊分頁(yè)就用&page=;當(dāng)你的地址后面沒有后綴或者只有?page=,那么點(diǎn)擊分頁(yè)就用?page=
4、獲取當(dāng)前頁(yè)碼
這里的頁(yè)碼必須是整數(shù),所以可以用ceil這個(gè)函數(shù),還要注意用戶的惡意修改地址!
4、做分頁(yè)元素,這里只是做一個(gè)簡(jiǎn)單的數(shù)字分頁(yè),更復(fù)雜用戶體驗(yàn)更好的,大家可以自行擴(kuò)展!
5、設(shè)置數(shù)據(jù)庫(kù)庫(kù)的查詢條數(shù),也就是LIMIT;舉個(gè)例子:比如我現(xiàn)在有10條數(shù)據(jù),設(shè)置每頁(yè)顯示5條數(shù)據(jù),那么
當(dāng)用戶點(diǎn)擊第一頁(yè)時(shí),LIMIT 0,5
當(dāng)用戶點(diǎn)擊第二頁(yè)時(shí),LIMIT 5,5
6、這段代碼的調(diào)用:
$_page = new Page(10,5);
$_page->page();
上面的10是總的數(shù)據(jù)個(gè)數(shù),5是你想要每頁(yè)顯示數(shù)據(jù)的個(gè)數(shù),$_page->page()就是頁(yè)面的分頁(yè),直接echo出來(lái)就行啦,注意你還得將Page類中的$_limit調(diào)用出來(lái)放到數(shù)據(jù)庫(kù)查詢語(yǔ)句中,這樣基本的php分頁(yè)就出來(lái)啦!