Quick Tip: Getting the Next and Previous Items or Posts

It is a common requirement in lots of projects to fetch the next and previous items or posts and display a link to them on every item or post page. Getting the previous and next item can be quite tricky especially if they need to be user-specific, although it is very easy. I'll show you how -

function nextItem($item_id) {
  $sql = "SELECT * FROM item WHERE id > $item_id AND user_id='{$_SESSION['user_id']}' ORDER BY ID LIMIT 1";
  // Fetch and return the item
}

function prevItem($item_id) {
  $sql = "SELECT * FROM item WHERE id < $item_id AND user_id='{$_SESSION['user_id']}' ORDER BY ID DESC LIMIT 1";
  // Fetch and return the item
}

Instead of 2 round-trips, you can even query the DB once. The trick is to use UNION :)







Last Updated On : 7th February 2012

Subscribe to get updates delivered to your inbox

Leave a comment