Selecting the next valid ID from a table (very easy, help me in 2 seconds :P)

Discussion in 'MySQL' started by Kendothpro, Jun 30, 2006.

  1. #1
    I have a database with photos, but I sometimes delete them
    The problem is, I have a PHP script that lets you view the photos, and it has a "next" and "previous" link

    To get the next photo, I get the current ID, then add 1, then query the db
    But let's say I have deleted some photos, and my ID column is like this

    1000
    1005
    1006

    If I'm at the photo with ID 1000, how can I find out the next valid ID (i.e. 1005) without blindly adding +1 to the current value? Is there a mysql/php function for that? or do I have to recursively query the db until I find a valid ID (seems stupid) ?

    Thanks
     
    Kendothpro, Jun 30, 2006 IP
  2. dct

    dct Finder of cool gadgets

    Messages:
    3,132
    Likes Received:
    328
    Best Answers:
    0
    Trophy Points:
    230
    #2
    Do something like this for next
    
    select * from photos where id > 1000 order by id asc limit 1
    
    Code (sql):
    and for previous

    
    select * from photos where id < 1000 order by id desc limit 1
    
    Code (sql):
    Totally untested but you should get the idea
     
    dct, Jun 30, 2006 IP
  3. Kendothpro

    Kendothpro Well-Known Member

    Messages:
    574
    Likes Received:
    25
    Best Answers:
    0
    Trophy Points:
    120
    #3
    Hmm thanks that's clever :)
     
    Kendothpro, Jun 30, 2006 IP