0

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
  • This is generally carried out via a scripting language - are you using one? (If not simply use SELECT LAST_INSERT_ID();. If however you're using a scripting language you need to use the language specific means if there is one.) Commented Feb 8, 2011 at 21:02
  • possible duplicate of [Select last insert id ](stackoverflow.com/questions/2266604/select-last-insert-id) Commented Feb 8, 2011 at 21:23

2 Answers 2

3

LAST_INSERT_ID() returns automatically generated AUTO_INCREMENT value.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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?
@MarathonStudios Are you accessing MySQL via a scripting language such as PHP? If so, this isn't the correct approach to use.
@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."
@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.
So what's the final conclusion here, is mysql_insert_id thead-safe (under php5.3)?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.