1

I have a database that stores image urls andother data, I want a gallery to display them but because the site is public I may want to delete some images. When a user uploads an image source and title, it is inserted into the database with an auto increment unique ID. The current script only adds or subtracts 1 from the ID to display the next or previous image. Is there any better way of doing this? My current script:

function image_control($id){
$next=$id+'1';
$prev=$id-'1';
$query = "SELECT MAX(id), MIN(id) FROM mp_images";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
    $max = $row['MAX(id)']; $min = $row['MIN(id)'];
}
if($next==$max+"1"){$next=$min;} if($prev==$min-"1"){$prev=$max;}
echo "<a href='".$next."'>Next Image</a> <a href='".$prev."'>Previous Image</a>";
}

An example of this failing would be images where the ID's are 3,4,5,7,8.

Blease
  • 1,380
  • 4
  • 38
  • 64
  • 3
    Please stop writing new code with the ancient `mysql_*` functions. They are no longer maintained and community has begun the [deprecation process](http://goo.gl/KJveJ) . Instead you should learn about [prepared statements](http://goo.gl/vn8zQ) and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you cannot decide, [this article](http://goo.gl/3gqF9) will help to choose. If you care to learn, [here is a good PDO-related tutorial](http://goo.gl/vFWnC). – vascowhite May 21 '12 at 19:49
  • vascowhite is right, however his link to the article to learn more is not very helpful. I found [this stackoverflow answer](http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons) much more informative. – random_user_name May 21 '12 at 19:55

1 Answers1

5

some pseudo code for getting the next id:

$nextId = SELECT id FROM mp_images WHERE id > $currentId ORDER BY id ASC LIMIT 1
if ( no results )
  // no next image

and for the previous:

$prevId = SELECT id FROM mp_images WHERE id < $currentId ORDER BY id DESC LIMIT 1
if ( no results )
  // no previous image

It's up to you on what to do if there is no next image (you could for instance fetch the first image) or no previous image (you are on the first image).

Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
  • Would you be able to tell me how to fetch the next image after a break? E.g. if it was on 7 and 8 was missing, how would I fetch 9? – Blease May 21 '12 at 19:53