Next value in a random order of numbers

2

I'm trying to create a NEXT button, this Next will show the next content, all of which are stored in the database and all have an ID.

Everything would be very simple if the IDs were sequential type 1 2 3 4 5 6 7, but it is not ... And that's where I'm having the problem ...

In the filtering of data (AS A CATEGORY), the IDs are no longer sequences of type 1 3 4 7.

I am using PDO, I filter the IDs of that category in question, but I can not create the NEXT button.

    
asked by anonymous 22.05.2014 / 19:31

1 answer

5

If the IDs are in ascending order (1, 4, 37, 1278, 12888):

SELECT id FROM artigos WHERE id > (PONHA O ID ATUAL AQUI) ORDER BY id LIMIT 1 

and to get the above:

SELECT id FROM artigos WHERE id < (PONHA O ID ATUAL AQUI) ORDER BY id DESC LIMIT 1 

Applying to the PDO, including the category filter:

$stmt = $con->prepare('SELECT id FROM artigos WHERE id > ? AND categoria = ? ORDER BY id LIMIT 1');
$stmt->bindParam(1, $idAtual, PDO::PARAM_INT);
$stmt->bindParam(2, $codCategoria, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$nextId = $result['id'];
  

This solution also works if the% s of% s are not in numerical order, just change the id of the WHERE and ORDER to the desired field in the ordering as long as they are unique. p>

Example

SELECT id FROM artigos WHERE titulo > (PONHA O titulo ATUAL AQUI) LIMIT 1 ORDER BY titulo
    
22.05.2014 / 19:38