'Get next and previous in sql with a loop

A topic has images attached. I use these two queries to be able to open the previous and next image with a link. When you get to the last picture, you only have the option to get to the previous one and when you get to the first, you can only go to the next one. However, it wants to have a loop. This means when you get to the last one and you click on next, the first one will be loaded and when you get to the first and keep clicking on before, the last one will be loaded. I think a "loop" described it very well.

Is this possible with SQL in a simple query?

previous SQL:

SELECT * FROM attachments WHERE 
attach_id < 9580 
AND topic_id = 109331
ORDER BY attach_id DESC LIMIT 1

previous PHP:

while ($prevrow = $db->sql_fetchrow($result))
{
$previd  = $prevrow['attach_id'];
}

next SQL:

SELECT * FROM attachments WHERE 
attach_id > 9580 
AND topic_id = 109331
ORDER BY attach_id DESC LIMIT 1

next PHP:

while ($nextrow = $db->sql_fetchrow($result))
{
$nextid  = $nextrow['attach_id'];
}

Thank you very much.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source