简体   繁体   中英

mysql previous/next id and cycle

I have set up my code to get the previous and next id. But once it hit the last or beginning of the numbers, it won't let me go next or previous, respectively.

This is how I set my sql query

$pre = mysql_query("SELECT iID,userID FROM images WHERE iID < # AND userID = 4 ORDER BY iID DESC LIMIT 1"); 
$nex = mysql_query("SELECT iID,userID FROM images WHERE iID > # AND userID = 4 ORDER BY iID ASC LIMIT 1");

Can someone help me cycle the query? So if it hits the lowest number, or the largest number, it will go back cycle

ex:

iID     userID

3        4
4        0
5        4
10       4

So if I cycle through all the userID with 4 and currently it will show iID, 5, I can click previous and next and it will then go to iID 3 and 10, respectively. But when it hits 3 or 10, it is the max. I would like to continue through the query. So if I hit previous, it will go 3, and if I hit previous again, it will go to 10, and then 5, and then 3, then back to 10...

Can someone help me?

THanks

If you get the min and max iID's you have a range you can check from

UPDATE (this should return two values min/max):

SELECT MAX(iID) AS max_iid, MIN(iID) AS min_iid
FROM images
WHERE userID = 4

PHP:

// Check if image is between the min/max
if($iID <= $max_iid && $iID >= $min_iid) {
    // display image

// if image id is greater than the max, display the min id
} elseif($iID > $max_iid) {
    // display min_iid image

// else display the max image id
} else {
    // display max_iid image
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM