MySQL: Getting a newly created entry's id

Salvatos

Member
Prime Account
Messages
562
Reaction score
1
Points
18
Hi
I don't know if I can do what I'm asking for and if I can, I don't know where to find the info.

To make it short, I have a script that creates a database entry but needs to refer to it right after. But I cannot know the info it will insert in advance. How can I get that entry's id?

I could simply get the latest id, but I am afraid that the script could be used by two or more people at once and there would be a confusion of the correct entry to use.

Since PHP is server side, is it sufficient to assume that the latest id/entry will be the one created by this very user at this very moment (100% sure) or not? And if not, is there another way to know which entry was just created (since none of the info inserted is unique)?
I used to create a customized secondary id that could be found right away using the variables used to create it, but it's rather inefficient resource-wise considering that the primary id key is already unique and much shorter thanks to the auto increment.

Thanks in advance for the advice!
 

TheMan177

New Member
Messages
179
Reaction score
0
Points
0
If I understand your question correctly, I don't think you'll have a problem. This operates using the script's last connection, and even if you have multiple users at once, each instance of that script should have its own seperate link to MySQL.

MySQL's manual states:

http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html said:
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 non-magic 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.
 

Salvatos

Member
Prime Account
Messages
562
Reaction score
1
Points
18
Thanks a lot!
To be honest I didn't even know about LAST_INSERT_ID() (still a beginner) so I'll have a look at it and according to your quote it's gonna be exactly what I should have done from the start.

Added to your rep!
 
Top