I am using an INSERT to create a new record in my database which is identified by an autonumber field "product_id". Immediately after I insert the row, I need to get the ID of the new row so I can output the info for further processing. Is there any mysql function to get this ID?
2 Answers
See: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
Note: this is assuming the c api.
From the text:
20.8.10.3. How to Get the Unique ID for the Last Inserted Row
If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.
6 Comments
MarathonStudios
This will work perfectly for this app, but just out of curiosity, will this be safe to use in large applications with many concurrent selects being streamed in?
John Parker
@MarathonStudios Are you accessing MySQL via a scripting language such as PHP? If so, this isn't the correct approach to use.
HBlend
@MarathonStudios: Assuming threaded C, if each thread has its own connection to the db, you should be safe. From the docs: "The value of mysql_insert_id() is affected only by statements issued within the current client connection. It is not affected by statements issued by other clients."
John Parker
@MarathonStudios PHP does indeed have a dedicated mysql_insert_id function that's thankfully named the same thing as the C API function @HBlend mentions. Incidentally, if you'd tagged this question as PHP you'd have had a more relevant/accurate answer earlier.
Teson
So what's the final conclusion here, is mysql_insert_id thead-safe (under php5.3)?
|
SELECT LAST_INSERT_ID();. If however you're using a scripting language you need to use the language specific means if there is one.)