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 itemID desc LIMIT 1), (select itemID from tableName where itemID = $curID), (select itemID from tableName where itemID > $curID order by itemID asc LIMIT 1) ) "; $result = mysql_query($sql); while ( $row = mysql_fetch_array( $result ) ) { if ( $row['itemID'] == $curID) $curRow = $row; else if ( $row['itemID'] < $curID ) $prevID = $row['itemID']; else if ( $row['itemID'] > $curID ) $nextID = $row['itemID']; } // DEBUG stuff echo "<font color=red>prevID=" . $prevID . "</font><br>"; echo "<font color=red>curID=" . $curID . "</font><br>"; echo "<font color=red>nextID=" . $nextID . "</font><br>"; echo "<font color=red>lastID=" . $lastID . "</font><br>"; echo "<font color=red>sql=" . $sql . "</font><br>"; // The postDate column in this case has the value like '2010-05-11' // There is probably a better way to handle dates, but this is the data I was given $dateArray=explode('-', $curRow['postDate']); $postDate = date('M j, Y', mktime(0, 0, 0, $dateArray[1], $dateArray[2], $dateArray[0])); mysql_close($link); mysql_free_result($result); // Print the next/prev links $self = $_SERVER['PHP_SELF']; $first = ''; $prev = ''; $next = ''; $last = ''; if ($curID > 1) $first = " <a href=\"$self?curID=1\"><< First </a> "; if ($nextID != NULL) $next = " <a href=\"$self?curID=$nextID\">Next ></a> "; if ($prevID != NULL) $prev = " <a href=\"$self?curID=$prevID\">< Prev </a> "; if ($lastID != $curID) $last = " <a href=\"$self?curID=$lastID\">Last >></a> "; // print the page navigation link // There is probably a better way to do this to, but this is the code I was given. echo '<br><div id="navigator" align="center">'; echo $first . " " . $prev . " <b>" . $postDate . "</b> " . $next . " " . $last;
Comments
Post a Comment