Jump to content

Next/Previous rows


The Little Guy

Recommended Posts

How can I get the next four and previous four rows?

 

Here is what I have and it isn't working at at all.

$q1 = Mysql::query("SELECT id, file, dir FROM photos WHERE id > $id AND album = '$al' ORDER BY id ASC LIMIT 4");
$q2 = Mysql::query("SELECT id, file, dir FROM photos WHERE id < $id AND album = '$al' ORDER BY id DESC LIMIT 4");

Link to comment
Share on other sites

LIMIT has an optional offset you can specify.  Keep track of the current offset with a variable, changing the offset as you move from next to previous in your code (however you do that, clicking on a link or with a loop or whatever).  Offset should be (n-1)*numrows  subtracting 1 from n because as with everything else rows start with 0, and then multiplying by number of rows you are selecting (in this case 4).  I suggest you read a pagination tutorial as part of pagination is doing something like this.

Link to comment
Share on other sites

Here is what I have for a query. I have 2 problems.

 

(SELECT id, file, dir, 'prev' as direction FROM photos WHERE id < 19 AND album = '2' ORDER BY id ASC LIMIT 4)
union
(SELECT id, file, dir, 'curr' as direction FROM photos WHERE id = 19)
union
(SELECT id, file, dir, 'next' as direction FROM photos WHERE id > 19 AND album = '2' ORDER BY id DESC LIMIT 19, 4)

 

Problems:

 

1. there should ALWAYS return 4 values with my limit 4. next has no more rows, go to the beginning. If prev has no more rows, get the last

 

2. the thrid query in my union, is in the wrong direction. if I have 19 as the id, I get "23, 22, 21, 20" But if I change DESC to ASC, I get "39, 40, 41, 42". How can I reverse those?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.