25.2.13.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.
You can check from your C applications whether a value was
stored in an AUTO_INCREMENT
column by
executing the following code (which assumes that you've
checked that the statement succeeded). It determines whether
the query was an INSERT
with an
AUTO_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);
}
For more information, see Section 25.2.3.36, “mysql_insert_id()
”.
When a new AUTO_INCREMENT
value has been
generated, you can also obtain it by executing a
SELECT LAST_INSERT_ID()
statement with
mysql_query()
and retrieving the value from
the result set returned by the statement.
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
).
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 NULL
INSERT INTO foo2 (id,text)
VALUES(LAST_INSERT_ID(),'text'); # use ID in second table
Note that mysql_insert_id()
returns the
value stored into an AUTO_INCREMENT
column,
whether that value is automatically generated by storing
NULL
or 0
or was
specified as an explicit value.
LAST_INSERT_ID()
returns only automatically
generated AUTO_INCREMENT
values. If you
store an explicit value other than NULL
or
0
, it does not affect the value returned by
LAST_INSERT_ID()
.