Reputation: 11
I understand the lastInsertId
or mysqli_insert_id
function returns the last inserted id of the insert or update query but say you had two intending users filling out a form in different locations at the same time and user2's id was the last at the time the mysqli_insert_id
on user1's script was being run instead of user1's id.
will the id returned be user2's id or user1's id? I know the script will run in micro or milliseconds and its possible the scenario might not ever occur but is it possible that the returned id in a case where two intending users post form data at the same time can be different from the actual id that should be returned.
I hope the question is pretty clear. I am also very new to programming so pardon me.
I would also like to thank all the contributors on stack exchange, I have learnt alot in a very short while.
Upvotes: 1
Views: 103
Reputation: 49
You can use LAST_INSERT_ID().
It will get you the latest row inserted in a table i.e the last row for you.
Upvotes: -1
Reputation: 180024
Nothing to worry about here.
They all call the underlying MySQL functionality.
For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client. It is not even changed if you update another AUTO_INCREMENT column with a nonmagic value (that is, a value that is not NULL and not 0). Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid. Each client will receive the last inserted ID for the last statement that client executed.
Upvotes: 3