开发者

PHP/SQL creating links to next row in a database

Lets say i have a databse:

+----------+
| Database |
+----------+
| id       |
| image    |
| category |
+----------+

Now i have a page that shows an image from the database, i want to add a

<< Previous image

and

Nex开发者_Python百科t image >>

button. I could just take the $id and add +1 , but what if the next ID does not exist in the DB ?

Any help appreciated, thanks

So i found this:

SELECT * 
  FROM database AS c 
 WHERE (id = (SELECT MAX(id) FROM database WHERE id < c.id AND language = 'en')
    OR  id = (SELECT MIN(id) FROM database WHERE id > c.id AND language = 'en'))

But how do i make a link out of it, like: <a href="domain.com/$c ??">Next</a> ?


You'll have to use another select:

SELECT
    ( SELECT ID FROM <TABLE-NAME> WHERE ID > $currentID ORDER BY ID ASC LIMIT 1 )
    AS NEXT_VALUE,
    ( SELECT ID FROM <TABLE-NAME> WHERE ID < $currentID ORDER BY ID ASC LIMIT 1 )
    AS PREV_VALUE
FROM DUAL;


As explained in this answer, you can use a subselect query to get the ID of the previous and next records:

...
WHERE id IN (
  '$id',
  (SELECT MAX(id) FROM yourTable WHERE id < '$id'),
  (SELECT MIN(id) FROM yourTable WHERE id > '$id')
)
... 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜