I have a photo gallery that has a previous and a Next link. When it gets to the last image it stops there. I want it to start over at the first picture. The fu开发者_如何学Gonction is a for loop and I think it should be a while loop and some things changed to make it an infinite loop. I just don't know how to convert this function. Still not that strong in PHP. Any help is appreciated.
$query = "SELECT pho_id FROM album_photos WHERE alb_id='$alb_id' ORDER by srt_id ASC";
$ret = mysql_query($query);
$num = mysql_numrows($ret);
for ($i = 0; $i < $num; $i++)
{
$row = trim(mysql_result($ret, $i));
if ($row == $pho_id)
{
$cur = $i;
$forw = @trim(mysql_result($ret, ($i+1))) or $forw = NULL;
$back = @trim(mysql_result($ret, ($i-1))) or $back = NULL;
}
}
$query = "SELECT * FROM photos WHERE pho_id='$back'";
$rets = mysql_query($query);
$back_good = mysql_numrows($rets);
$query = "SELECT * FROM photos WHERE pho_id='$forw'";
$rets = mysql_query($query);
$forw_good = mysql_numrows($rets);
$back = "photo-$per_id-$back-$alb_id.html";
$forw = "photo-$per_id-$forw-$alb_id.html";
if (strstr($back, 'pho_id=&') || $back_good == 0) { $back = NULL; }
if (strstr($forw, 'pho_id=&') || $forw_good == 0) { $forw = NULL; }
$ret = array();
$ret['back'] = $back;
$ret['next'] = $forw;
$cur++;
$ret['viewing'] = "Photo $cur of ".($num);
if($ret['back'] == NULL){
$ret['back'] = "";
$spacer = str_repeat(' ',12);
}
if($ret['next'] == NULL){
$ret['next'] = "";
$spacer = str_repeat(' ',12);
}
I suggest modifying your loop's if content like this.
$cur = $i;
//compute the indexes of the next and previous elements
//the next item is the first if we are at the end.
$forward_index = $i == $num - 1 ? 0 : $i + 1;
//the previous one is the last if we are at the beginning.
$backward_index = $i === 0 ? $num - 1 : $i - 1;
//fetch the elements
$forw = @trim(mysql_result($ret, $forward_index));
$back = @trim(mysql_result($ret, $backward_index));
//exit the for loop
break;
It is true you could turn the for loop into a while loop. However, there is no absolute need for this. I added a break statement in order to quit as soon as you locate the element you want to load.
Edit: fixed the code as per the OP comment. Silly mistake
精彩评论