PHP / MySQL How to Get Previous / Next Record ( ref / id ) Order by (non-exclusive) Date ASC / DESC

Ok, I’ve spent quite a while googling this and didn’t find the exact solution to what I thought was a very common issue: getting the previous and next references to a list that is ordered by date and the date not being exclusive.

The solutions I found all depended on a different date. So, here is my solution:

1.you pre-load the list of references as ordered in your original (I created a function for this):

if (!function_exists("getArr")) {
function getArr($ref, $table, $crit, $order) {
$arr = array();
$sql = "SELECT $ref as ref FROM $table WHERE ($crit) ORDER BY $order";
$res = mysql_query($sql) or die(mysql_error());
$tot = mysql_num_rows($res);

$prev = NULL;
if($tot>0) {
while ($row = mysql_fetch_assoc($res)) {
$arr[$row['ref']]['prev'] = $prev;
if($prev!=NULL) { $arr[$prev]['next'] = $row['ref']; }
$prev = $row['ref'];
}
}
@mysql_free_result($res);
return $arr;
}}

So now you can call, for example:
$pn = getArr(“myid”,”mytable”,”1=1″, $order=”mydate DESC, ref DESC”)

and have the ids for prev/next in
$pn[mycurrentref]['prev'] and $pn[mycurrentref]['next']

Hope it helps anyone ;-)
Mike