Next value in a random order of numbers

Asked

Viewed 109 times

2

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

Everything would be very simple if the ID were sequential type 1 2 3 4 5 6 7, but it’s not... And that’s where I have the problem...

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

I am using PDO, I filter the Ids of that category in question, but I cannot create the NEXT button.

1 answer

5


If 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 previous:

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

Applying to PDO, including 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 ids are not in numerical order, just change the id WHERE and ORDER by the desired field in the ordering, provided they are unique.

Example

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

    Thank you very much... Solved my problem...

  • In the example you gave me Cvoce showed how it would work if the ID’s were in ascending order (1, 4, 37, 1278, 12888), for this it was only to use the sign '>'. Supposing the id’s are not ordered crescently like: (1 4 20 10 15) how can I still skip to the next post?

  • Just follow the last example (last line of the answer), and sort by any field other than the ID. (in the example I used title, but you can use the field you want).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.