You can call the mysql_insert_id() function to return the value generated by the previous INSERT or UPDATE statement for an AUTO_INCREMENT column.
Syntax
my_ulonglong
mysql_insert_id(MYSQL *mysql)
Return values
The return values of mysql_insert_id() comply with the following rules:
If an
AUTO_INCREMENTcolumn exists and the automatically generated values are inserted into the column, the first value is returned.If
LAST_INSERT_ID(expr)is used in a statement,expris returned, even if anAUTO_INCREMENTcolumn exists.The return value varies based on the statement used:
When you call this function after an
INSERTstatement, if anAUTO_INCREMENTcolumn exists in the table and some values corresponding to this column are inserted into the table, the last value in this column is returned. If no rows is inserted,mysql_insert_id()returns 0.If an
INSERT ... SELECTstatement is executed, and no automatically generated value is inserted,mysql_insert_id()returns the ID of the last inserted row.When you call this function after an
INSERT ... ON DUPLICATE KEY UPDATEstatement, if anAUTO_INCREMENTcolumn exists in the table and some values corresponding to this column are inserted or updated, the last one of the inserted or updated values is returned.
Errors
None.
Notes
Call this function after you execute an INSERT statement on a table that contains an AUTO_INCREMENT field, or after you use INSERT or UPDATE to set a column value with LAST_INSERT_ID(expr).
For a stored procedure, mysql_insert_id() returns 0 after a CALL statement is executed. In this case, mysql_insert_id() applies to CALL, not the statement within the procedure. Within the procedure, you can use LAST_INSERT_ID() at the SQL level to obtain the AUTO_INCREMENT value. LAST_INSERT_ID() is easier to use in scripts.