what you need to do is get all the id entries from the database and put them into an array so you get :
array number 1 id 21
array number 2 id 37
array number 3 id 741
array number 4 id 5
so you then know what is the before and after by checking where in the array your current value is and you put those values into your buttons
sorry not even pseudocode, but that should give you the idea..
key terms: associative array, array, key , value