I did something pretty similar where I had users posting comments on pictures. I wanted to display the most recent one on top in the first page and then onwards in descending order. Here is what I did -
In my code, page number start from 1. The table's index is called commentid which is auto incremented.
define (MAX_COMMENTS_IN_PAGE, 10);
$query = "SELECT count(commentid) FROM commentstable";
// now execute the query - I used MySQL.
$numComments = // set your query result from above;
/* get the number of pages by dividing number of comments by the max number of comments in a page */
$numPages = (Integer)($numComments / MAX_COMMENTS_IN_PAGE);
/* interesting case where the above division leaves a remainder. For example, you have 11 comments, then the above division will yield 1 as the result, but then you need 2 pages with the second page containing the last comment. You can also do this nicely in the division result in the previous statement itself by using the ceil() function. Anyways ....*/
if( ($numComments % MAX_COMMENTS_IN_PAGE) > 0 )
$numPages++;
/* this is just a check to make sure we have the right page number. $page is coming from the GET request */
if( $page > $numPages )
$page = 1;
$startLimit = ($page - 1) * MAX_COMMENTS_IN_PAGE;
$endLimit = MAX_COMMENTS_IN_PAGE;
/* this should return values from the most recent up to the limit for the page */
$query = "SELECT * FROM commentstable ORDER BY commentid DESC LIMIT $startLimit, $endLimit";
/* output html - blah blah blah */
The problem with using the BETWEEN is that it assumes that the rowids are continuous. If a row is deleted, it'll have problems. So I thought, using the LIMIT is probably the best way.
I'm a novice in SQL, so this is as far as I could get. If there is a better solution, I'd love to see and incorporate!
Thanks ...