3

I have a comment system with pagination, 10 per page. I want to make permalinks to the comments. I'd like to be able to have the script figure out what page the comment is on without having to specify the page number and without excessively large queries or processing. So, for example, a link to a comment on page 5 would open the browser on comment page 5 and #scrolled to the comment (as opposed to showing the comment on it's own page).

I had thought to use 2 mysql queries, one SELECT all CommentId and then php array_search to find the position in the result and from that I could calculate what page it would be on. A 2nd query would get the page of comments required. This seems quite inefficient though especially if there are a lot of comments Ids to pull.

Could anyone suggest a simpler or more efficient way?

4

2 回答 2

3

好吧,如果您知道每页的评论数并且没有改变,那么您应该能够从 MySQL 中计算。如果您的浏览器永久链接中包含comment_id,则类似于:

select
    count(*)
from
    comments c
where
    comment_id < $comment_id
and
    topic_id = $topic_id -- or whatever

然后使用 PHP 中的这个数字,您将能够计算要在数据库中查找和显示的页面。

于 2012-04-23T18:30:35.087 回答
3

这一切都可以用 SQL 很容易地完成,假设这comment_id是某种形式的自动递增数字,这应该返回确切的页面:

SELECT FLOOR(COUNT(*)/$comments_per_page) FROM COMMENTS 
   WHERE ENTRY_ID = $entry_id AND comment_id < $comment_id;

当然,这是假设“平面评论”(没有父子关系)。显然,$comments_per_page是显示在每个页面上的评论数量(这可能只是一个常数),$entry_id指的是发表评论的博客/论坛帖子,并且$comment_id是您正在寻找的评论。

于 2012-04-23T18:31:15.720 回答