添加PHP分页 [英] Adding PHP Pagination
问题描述
我有一个SQL查询,该查询输出一堆符合特定条件的行.我正尝试在此过程中添加分页,以便更易于使用.
I have a SQL query that outputs a bunch of rows that match a certain criteria. I'm trying to add pagination to this process so that it's easier to use.
我的过程是这样的:
- 找出此页面的下限,找出此页面的上限(例如1-20、21-40等)
- 从MySQL表中拉出这些行
- 列出这些行
- 如果数量超过20,则添加
floor($totalRows / 20)
页 - ???
- 分页
- Figure out the lower limit of this page, figure out higher limit of this page (ex. 1 - 20, 21 - 40, etc.)
- Pull those rows from the MySQL table
- List those rows
- If there are more than 20, add
floor($totalRows / 20)
pages - ???
- Pagination
我的分页似乎工作正常,但是最后一页(无论可能是哪一页)列出的行数都比应有的行数少.这是我的代码:
My pagination seems to be working semi-properly, but the last page (whatever it may be) lists one less than the amount of rows it should. Here's my code:
$page = $_GET["p"];
$bL = (($page - 1) * 20) + 1;
$tL = $page * 20;
$total = mysql_num_rows(mysql_query("SELECT id FROM coupons WHERE zone = '$zone' AND dateExp > CURDATE()"));
if($tL > $total)
{
$tL = (($page - 1) * 20) + ($total % 20);
}
$gotRows = "SELECT * FROM coupons WHERE zone = '$zone' AND dateExp > CURDATE() ORDER BY retailerName LIMIT " . $bL . ", " . $tL;
//list all those rows
$numPages = floor($total / 20) + 1;
echo "<p id='results'>" . $total . " result" . $plural . " · Displaying " . $bL . " to " . $tL . " </p>";
echo "</table>";
$pG = 1;
while($pG <= $numPages)
{
if($pG == $page)
{
echo $pG;
}
else
{
echo "<a href='zone?z=" . $zone . "&p=" . $pG . "'>" . $pG . "</a>";
}
if($pG != $numPages)
{
echo "·";
}
$pG = $pG + 1;
}
有帮助吗?
没关系,我解决了行问题.但是我的页面底部链接错误的问题仍然存在.在第1页上,它可以正常工作-"1"不是链接,"2"是链接.但是,在第2页上,仅显示"1"作为链接. "2"不显示.
Nevermind, I solved the rows problem. But my problem with the page links on the bottom being wrong still persists. On page 1, it works properly - "1" is not a link, "2" is. On page 2, however, only "1" as a link shows. "2" doesn't show.
推荐答案
这种逻辑使我感到困惑.如果$tl
大于总数,是否会简单地等于总数?
This logic confuses me. If $tl
is greater than the total, would it not simply be equal to the total?
if($tL > $total)
{
$tL = (($page - 1) * 20) + ($total % 20);
}
为什么不呢?
$tL = ($tL > $total) ? $total : $tl;
此外,我将使用SQL而不是mysql_num_rows
来找到您的总数.它应该证明更可靠(特别是当您停止使用真正的旧版mysql扩展时).也许它还会返回正确的总数.
Also, I would use SQL to find your total instead of mysql_num_rows
. It should prove a little more reliable (especially when you stop using the really old mysql extension). Maybe it will also return the correct total.
SELECT COUNT(id) FROM coupons WHERE zone = '$zone' AND dateExp > CURDATE()
除此之外,我没有看到任何明显的东西可以解释错误的行数.
Other than this I am not seeing anything obvious that would explain an incorrect number of rows.
这篇关于添加PHP分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!