6
I want to take the last record registered in a database table, ie the value of AUTO_INCREMENT
from the table, I tried using:
SELECT MAX(id) as max FROM people
It works, but if I have no record in the table it will return NULL
, what may be wrong, because not always that return NULL
the table is new, for example:
Create 5 record in the table, and right after that I delete the 5, mine query will return the
NULL
while should return the 5 (which was the last to be registered, regardless of whether it was deleted or not).
I read about the lastInsertId() of PDO, but in the examples, it is always necessary to execute a query of INSERT
before the lastInsertId()
.
What is the best way to get the current value of AUTO_INCREMENT
of a table at any time?
PS:. When I say 'at any time' I mean that you don’t need to enter, update or delete a record before you can pick it up.
take a look at this: http://stackoverflow.com/questions/6761403/how-to-get-the-next-auto-increment-id-in-mysql
– Jedaias Rodrigues
So you don’t want to get the id of the last record, but the current value of your right key?
– Fleuquer Lima
That’s almost always a problem. Once obtained the value and stored in a variable, how do you prevent it to change externally and not collide?
– Bacco
@Bacco I was also thinking about it, I think you will not have problem, because the time period that this variable is used is extremely short, use when I insert a data in the database, then the last to store as class id.
– Leonardo
@Fleuquer File yes, soon also it will be the same as the last registered, even if the last registered by chance tries to be deleted.
– Leonardo
There is no right or wrong, there is no right: https://pt.wikipedia.org/wiki/Condi%C3%A7%C3%A3o_de_corrida
– Maniero
@Bigown did not know this 'Race Condition', I read the article and researched more on the subject, I analyzed the code used and I believe that in the case will not occur such failure, because there are no simultaneous processes in the case, therefore, 'I think' that it will not occur. Thank you for quoting, one more knowledge :)
– Leonardo
Is there a mechanism to ensure that there will be no simultaneous processes? Especially in PHP I don’t usually see this.
– Maniero
I did it just waiting for the result of one, until it has that result it will not go to the other process. I always do it just like this, I don’t know if there’s any other way to avoid it.
– Leonardo