mysql分页偏移量,如何计算分页的偏移量?

本文探讨了在实现Web服务中分页功能时遇到的数学困惑,包括如何正确计算总页数、当前页的起始位置,以及如何动态生成上一页、下一页和最后页的链接。作者分享了使用MySQL LIMIT和OFFSET的计算公式,并给出了处理last, previous, next链接的具体步骤。
摘要由CSDN通过智能技术生成

I am working on a pagination feature in a web service I am writing, but my lack of math insight is killing me now.

I have a couple of keys: totalItems, currentItems, currentPage, totalPages, but also a couple of links to first, last, previous and next.

At this moment, I am doing the following calculations:

totalItems: number of rows in the table

currentItems: limit parameter from HTTP request

currentPage: start parameter divided by limit parameter

totalPages: number of rows in the table divided by limit. (Rounded up, 8.1 page = 9 pages)

I assume those calculations to be correct, what I am struggling with is the following:

first: start parameter is 1 with limit from the HTTP request

last: should be the first item of the last page, how do I calculate this correctly?

previous: should be the first item of the previous page, how do I do this?

next: should be the first item of the next page, how do I do this?

What I would like to ask, is: are my calculations correct? And how do I tackle the three problems with last, previous and next?

解决方案

If you work with mysql its

LIMIT offset, items_per_page

To calculate the offset u can use

$offset = ($page - 1) * $items_per_page;

Then replace the $page accordingly.

Last

$last_offset = ($totalPages - 1) * $items_per_page;

Previous

$previous_offset = (($currentPage - 1) - 1) * $items_per_page;

Next

$next_offset = (($currentPage + 1) - 1) * $items_per_page;

EDIT :

if ($previous_offset > 0) echo '

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值