Select Previous and Next Entry based on ID in MySQL

Here is an easy way to select the previous and next entry based on a given ID in MySQL, good for paginations in PHP.

To get the previous entry, query is “SELECT * FROM table_name WHERE id $current_id ORDER BY id ASC LIMIT 1″

You might think it’s easier to use (id – 1) or (id + 1) but it might return errors when id’s are deleted and the count is broken.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s