If you insert a record into a table that contains anAUTO_INCREMENT column, you can obtain the value stored into that column by calling themysql_insert_id() function.
You can check from your C applications whether a value was stored in anAUTO_INCREMENT column by executing the following code (which assumes that you've checked that the statement succeeded). It determines whether the query was anINSERT with anAUTO_INCREMENT index:
if ((result = mysql_store_result(&mysql)) == 0 && mysql_field_count(&mysql) == 0 && mysql_insert_id(&mysql) != 0){ used_id = mysql_insert_id(&mysql);} When a newAUTO_INCREMENT value has been generated, you can also obtain it by executing aSELECT LAST_INSERT_ID() statement withmysql_real_query() ormysql_query() and retrieving the value from the result set returned by the statement.
When inserting multiple values, the last automatically incremented value is returned.
ForLAST_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 anotherAUTO_INCREMENT column with a nonmagic value (that is, a value that is notNULL and not0). UsingLAST_INSERT_ID() andAUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid. Each client will receive the last inserted ID for the last statementthat client executed.
If you want to use the ID that was generated for one table and insert it into a second table, you can use SQL statements like this:
INSERT INTO foo (auto,text) VALUES(NULL,'text'); # generate ID by inserting NULLINSERT INTO foo2 (id,text) VALUES(LAST_INSERT_ID(),'text'); # use ID in second tablemysql_insert_id() returns the value stored into anAUTO_INCREMENT column, whether that value is automatically generated by storingNULL or0 or was specified as an explicit value.LAST_INSERT_ID() returns only automatically generatedAUTO_INCREMENT values. If you store an explicit value other thanNULL or0, it does not affect the value returned byLAST_INSERT_ID().
For more information on obtaining the last ID in anAUTO_INCREMENT column:
For information on
LAST_INSERT_ID(), which can be used within an SQL statement, seeInformation Functions.For information on
mysql_insert_id(), the function you use from within the C API, seeSection 5.4.42, “mysql_insert_id()”.For information on obtaining the auto-incremented value when using Connector/J, seeRetrieving
AUTO_INCREMENTColumn Values through JDBC.For information on obtaining the auto-incremented value when using Connector/ODBC, seeObtaining Auto-Increment Values.