Question:
I have an array of users and I need to loop between them. It will work like this, every time someone makes a request on the page, I need the next user of the one chosen previously to be recorded in the database.
This is my array, which I get from registered users, this array can change.
array(
(int) 1 => 'Joao',
(int) 6 => 'Pedro',
(int) 7 => 'Luiz',
(int) 9 => 'Vinicius'
)
That is, if in the previous request Pedro
was chosen (I get the id that was saved previously), I need him to save the id
of luiz in the DB in the next one, and so on…
My doubt is, how to "walk" with the values of this array based on the last registered value?
Answer:
After randomly selecting a user from your database, you could use this query to select the "next" id after the current one:
SELECT * FROM sua_tabela WHERE id_usuario > $id_atual ORDER BY id_usuario ASC LIMIT 1
What the query basically does is bring up the next user with an id
greater than the current one, limiting the query to one result, that is, it only brings the next one.
In case the id
is already the last one in the list, a way to "reset" the loop would be to use an if
in PHP to reset the $id_atual
to the smallest possible.