tags:

views:

189

answers:

4

How can I do to get the next row in a table?

`image_id` int(11) NOT NULL auto_increment
`image_title` varchar(255) NOT NULL
`image_text` mediumtext NOT NULL
`image_date` datetime NOT NULL
`image_filename` varchar(255) NOT NULL

If the current image is 3 for example and the next one is 7 etc. this won’t work:

$query = mysql_query("SELECT * FROM images WHERE image_id = ".intval($_GET['id']));
echo $_GET['id']+1;

How should I do?

thanks

+3  A: 

You're very close. Try this:

$query = mysql_query("SELECT * FROM images
                     WHERE image_id > ".intval($_GET['id'])." ORDER BY image_id LIMIT 1");

    <?php echo $_GET['id'] ?>
Chris Pebble
+4  A: 
SELECT * FROM images WHERE image_id < 3 ORDER BY image_id DESC LIMIT 1 -- Previous
SELECT * FROM images WHERE image_id > 3 ORDER BY image_id LIMIT 1 -- Next
Greg
A: 

If you want to circle the records, you could use this:

-- previous or last, if there is no previous
SELECT *
FROM images
WHERE image_id < 12345 OR image_id = MAX(image_id)
ORDER BY image_id DESC
LIMIT 1

-- next or first, if there is no next
SELECT *
FROM images
WHERE image_id > 12345 OR image_id = MIN(image_id)
ORDER BY image_id ASC
LIMIT 1
Gumbo
A: 

Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Paul Tarjan