Sounds rather complicated to me. If it's not too much of a hassle, I would suggest that you redesign your database to use img_id as the primary key (assuming that it is unique). You could then easily calculate the before and after img_id values and select them from the database in 1 SQL query. (It would also be very quick since primary keys are indexed)
Then the SQL query (something like):
Hope this helps,
In reply to Re: Building an index for next/last in a photo album.