Skip to main content

Posts

Showing posts with the label MySQL PHP

Getting Next and Previous Item by ID From MySQL Database With PHP

If you know the ID of an item you want to get from a MySQL database with PHP, but you also want to get the next and previous items when the IDs are in numerical order but may contain gaps due to deleted items, you can do something like this: $curID = NULL; $curRow = NULL; $prevID = NULL; $nextID = NULL; $lastID = NULL; // Get the latest one (for the "Last" link) $result = mysql_query("SELECT itemID FROM tableName ORDER BY itemID desc LIMIT 1"); $row = mysql_fetch_array( $result ); $lastID = $row['itemID']; // Get the ID for the requested item if (isset($_GET['curID'])) { // if $_GET['curID'] defined, use it as curID $curID = $_GET['curID']; } else { // Use the latest one $curID = $lastID; } // Get requested row and next/prev rows if they are there $sql = " SELECT * FROM tableName WHERE tableName.itemID IN ( (select itemID from tableName where itemID < $curID order by i...