PHP 簡單分頁 獻給小白
阿新 • • 發佈:2019-02-13
echo max foreach mini user dev mysql cell scale
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>人員信息</title>
<?php
function page($pageNum = 1,$pageSize=3){
//1. 鏈接數據庫
$conn = @new mysqli("127.0.0.1","root","123");
if($conn->connect_errno){ //返回鏈接錯誤號
//返回鏈接錯誤信息
die("數據庫鏈接失敗:".$conn->connect_error);
}
//2. 選擇數據庫
$conn->select_db("collect") or die("選擇數據庫失敗:".$conn->error);
//3.設置字符集編碼
$conn->set_charset("utf8") or die("設置字符集失敗:".$conn->error);
//4. 準備SQL語句
$sql = "select * from page limit " . (($pageNum - 1) * $pageSize) . "," . $pageSize;
//5. 執行SQL語句,返回結果集或者布爾類型true/false
$res = $conn->query($sql);
$ress = array();
while( $row = $res->fetch_array()) {
$ress[] = $row;
}
$res->close();
$conn->close();
return $ress;
}
function allpage(){
//1. 鏈接數據庫
$conn = @new mysqli("127.0.0.1","root","123");
if($conn->connect_errno){ //返回鏈接錯誤號
//返回鏈接錯誤信息
die("數據庫鏈接失敗:".$conn->connect_error);
}
//2. 選擇數據庫
$conn->select_db("collect") or die("選擇數據庫失敗:".$conn->error);
//3.設置字符集編碼
$conn->set_charset("utf8") or die("設置字符集失敗:".$conn->error);
//4. 準備SQL語句
$sql = "select count(*) num from page";
//5. 執行SQL語句,返回結果集或者布爾類型true/false
$res = $conn->query($sql);
$obj = mysqli_fetch_object($res);
$res->close();
$conn->close();
return $obj->num;
}
$allNum = allpage();
//規定一頁顯示幾個人員信息
$pageSize = 3;
//分頁
$pageNum = empty($_GET["pageNum"])?1:$_GET["pageNum"];
$endPage = ceil($allNum/$pageSize); //總頁數
$array = page($pageNum,$pageSize);
?>
</head>
<body>
<table cellspacing="0" cellpadding="1" width="500" border="1" style="text-align: center">
<tr>
<th>編號</th>
<th>姓名</th>
<th>年齡</th>
</tr>
<?php
foreach ($array as $v){
echo "<tr>";
echo "<td>{$v[‘id‘]}</td>";
echo "<td>{$v[‘name‘]}</td>";
echo "<td>{$v{‘age‘}}</td>";
echo "</tr>";
}
?>
</table>
<div>
<a href="?pageNum=1">首頁</a>
<a href="?pageNum=<?php echo $pageNum==1?1:($pageNum-1)?>">上一頁</a>
<a href="?pageNum=<?php echo $pageNum==$endPage?$endPage:($pageNum+1)?>">下一頁</a>
<a href="?pageNum=<?php echo $endPage?>">尾頁</a>
</div>
</body>
</html>
PHP 簡單分頁 獻給小白