What’s the best solution to do this:
I’ve got a query (e.g. SELECT * FROM products WHERE category = 12 ORDER BY price DESC) and the user clicked on one of the products returned by this query.
So in this example the query returns the products 1,3,7,4,10,6,8,9 and 15. The user clicks on product 10. Now I want an “next” and a “previous” link to product 6 and to product 4.
How can I get those two ID’s ?
First you should note that your ordering is not well-defined.
If two objects have the same price the relative order of these two items is indeterminate and could change from query to query. So your order by needs to have a tie-breaker to guarantee that the order will be consistent. If you have an id field you can use that as a tie-breaker:
To implement next:
Previous is similar but with the condition and order reversed: