更新以包含完整代码。
我从数据库中提取记录,然后每页显示5条记录,如下所示:
$num_rec_per_page=5;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$school = $_REQUEST['school'];
$sql = "SELECT * FROM `data` WHERE `school` LIKE '%$school%'";
$rs_result = mysql_query($sql);
$total_records = mysql_num_rows($rs_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='search.php?school=".urlencode($school)."&page=".$i."'>".$i."</a>";
};
这为每个页面提供了一个很长的列表:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
我想做的是:
<Prev 1 2 3 4....53 54 55 Next>
答案 0 :(得分:1)
在LIMIT
查询中使用OFFSET
和SELECT
条款来实施分页。
以下是参考资料:
所以你的代码应该是这样的:
$num_rec_per_page = 5;
if(isset($_GET["page"])){
$page = $_GET["page"];
}else{
$page=1;
}
$offset = ($page - 1) * $num_rec_per_page;
$school = $_GET['school'];
$sql = "SELECT * FROM `data` WHERE `school` LIKE '%" . $school. "%' LIMIT 5 OFFSET " . $offset;
$rs_result = mysql_query($sql);
$total_records = mysql_num_rows($rs_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
for ($i=1; $i<=$total_pages; $i++){
if($i != 1){
$prev_page = $i - 1;
echo "<a href='search.php?school=".urlencode($school)."&page=" . $prev_page ."'><prev</a>";
}
echo " <a href='search.php?school=".urlencode($school)."&page=".$i."'>".$i."</a>";
if($i != $total_pages){
$next_prev = $i + 1;
echo " <a href='search.php?school=".urlencode($school)."&page=" . $next_page ."'>next></a>";
}
}
旁注:不要使用mysql_*
函数,从PHP 5.5开始不推荐使用它们,并且在PHP 7.0中完全删除它们。请改用mysqli
或pdo
。 And this is why you shouldn't use mysql_*
functions。