php下的分页原理学习
**首先确定分页需要确定的参数数据**
`page 当前页码`
`pageSize 每一页的条数`
`total_count 总共的数据条数`
`pageNumber = ceil ( totalCount / pageSize) 总共可以分为几页`
begin :
**1.首先需要正确的连接数据库查询下总条数信息**
//配置数据库信息 $host = "localhost:3306"; $username = "root"; $password = "";//密码 $db = "";//表名 //创建数据库链接 $conn = mysqli_connect($host, $username, $password, $db); if (!$conn) { echo "connect error"; exit; } if ($result = mysqli_query($conn, "SELECT COUNT(*) FROM 表名")) { $row = mysqli_fetch_assoc($result); $total_count = $row['COUNT(*)'];//获得总共的数据条数 }
php5.5 以后废弃了之前的mysql_XXX的 api 操作 改用 mysqli_XXX的 api;
**2.判断边界条件生成sql语句**
`sql`语句:`"SELECT * FROM 表名 LIMIT 起始位置,数量"`
//获得www.domain.com/xxx/xxx?page=num;url的参数 $page = $_GET['page']; //总共可分的页数 $pageNumber = ceil($total_count / $pageSize); if ($page <= 0 || $page > $pageNumber ) { echo '404';//非法的page参数直接返回404 exit; } else { $start = ($page - 1) * 10; } if($result = mysqli_query($conn, "SELECT * FROM 表名 LIMIT $start,10")){ while ($row = mysqli_fetch_assoc($result)) { echo $row['id'], ' ', $row['name'], "<br/>"; //查询出结果 } }
**3.前端分页的显示和url**
//边界条件判定来确定 `上一页` `下一页` 按钮的显示和是否可以点击; -1表示无效,即不可点击 if ($page <= 1) { $pre = -1; } else { $pre = $page - 1; } if ($page < $pageNumber) { $next = $page + 1; } else { $next = -1; } $path = $_SERVER["PHP_SELF"]; if ($pre == -1) { echo "<span class='pagination'>上一页</span>"; } else { echo "<a class='pagination' href='$path?page=$pre'>上一页</a>"; } if ($page == 1) { echo "<span class='pagination'>首页</span>"; } else { echo "<a class='pagination' href='$path?page=1'>首页</a>"; } //分页页码按钮的显示逻辑 // $paginationSize= 5; //默认显示5个连续的可点击分页页码按钮 //页码数量超过一定数值后显示前两页 if (($page + $paginationSize) > $next_limit) { $end_page = $next_limit; } else { $end_page = $page + $paginationSize; } if ($page > 4) { echo "<a class='pagination' href='$path?page=1'>1</a>"; echo "<a class='pagination' href='$path?page=2'>2</a>"; echo "<span class='point'>···</span>"; } for ($i = $end_page - $paginationSize; $i <= $end_page; $i++) { if ($i == $page) { echo "<span class='pagination'>$i</span>"; } else { echo "<a class='pagination' href='$path?page=$i'>$i</a>"; } } if ($page == $next_limit) { echo "<span class='pagination'>尾页</span>"; } else { echo "<a class='pagination' href='$path?page=$next_limit'>尾页</a>"; } if ($next == -1) { echo "<span class='pagination' >下一页</span>"; } else { echo "<a class='pagination' href='$path?page=$next'>下一页</a>"; }
end:
完整代码:
[github][1]
[1]: https://github.com/llauser/hand-demo/tree/master/php