要想寫出分頁代碼,首先你要理解SQL查詢語句:select * from goods limit 2,7。PHP分頁代碼核心就是圍繞這條語句展開的,SQL語句說明:查詢goods數(shù)據(jù)表從第2條數(shù)據(jù)開始取出7條數(shù)據(jù)。在分頁代碼中,7表示每頁顯示多少條內容,2通過公式計算表示翻頁數(shù),通過傳入不同參數(shù)替換“2”的值,即可篩選出不同的數(shù)據(jù)
index.php:
include 'conn.php'; //引入數(shù)據(jù)庫操作類
$conn=new conn(); //實例化數(shù)據(jù)庫操作類
$total=$conn->getOne('select count(*) as total from goods');
$total=$total['total']; //goods表數(shù)據(jù)總數(shù)據(jù)條數(shù)
$num=6; //每頁顯示條數(shù)
$totalpage=ceil($total/$num); //計算頁數(shù)
if(isset($_GET['page']) && $_GET['page']<=$totalpage){//這里做了一個判斷,若get到數(shù)據(jù)并且該數(shù)據(jù)小于總頁數(shù)情況下才付給當前頁參數(shù),否則跳轉到第一頁
$thispage=$_GET['page'];
}else{
$thispage=1;
}
//注意下面sql語句中紅色部分,通過計算來確定從第幾條數(shù)據(jù)開始取出,當前頁數(shù)減去1后再乘以每頁顯示數(shù)據(jù)條數(shù)
$sql='select goods_id,goods_name,shop_price from goods order by goods_id limit '.($thispage-1)*$num.','.$num.'';
$data=$conn->getAll($sql);
foreach($data as $k=>$v){
echo '//顯示分頁數(shù)字列表 for($i=1;$i<=$totalpage;$i++){ echo ''.$i.' '; }
上述代碼實現(xiàn)了一個最簡單的PHP分頁效果:
僅實現(xiàn)點擊翻頁數(shù)字顯示不同的翻頁數(shù)據(jù),可以在此基礎上進一步完善,只要基礎原理理解后,后續(xù)工作就比較容易開發(fā)了。
conn.php代碼:
/*
*連接數(shù)據(jù)庫 進行相關查詢操作
*/
class conn{
public function __construct(){
include_once('config.php');
try{
$this->pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '123456');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->exec('set names utf8');
}catch(PDOException $e){
echo '數(shù)據(jù)庫連接失敗:'.$e->getMessage();
exit();
}
}
//獲取一行數(shù)據(jù)
public function getOne($sql){
$rs=$this->pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
return $rs;
}
//獲取多行數(shù)據(jù)結果
public function getAll($sql){
$rs=$this->pdo->query($sql)->fetchall(PDO::FETCH_ASSOC);
return $rs;
}
}conn.php功能是完成數(shù)據(jù)庫連接,并實現(xiàn)取出數(shù)據(jù)操作方法,這里我使用的是pdo,這里可以根據(jù)大家習慣來組織代碼。
config.php:
* *配置數(shù)據(jù)庫信息 */ $cfg_dbhost='localhost'; $cfg_dbname='test'; $cfg_dbuser='root'; $cfg_dbpw='123456';
該例子僅是為了說明基礎的分頁原理,距真正使用還有很多修改地方。
上一篇: 常用的php標簽調用大全
下一篇: 如何修改或刪除phpcms后臺菜單
關鍵詞:



