mysql_insert_id()

2023-07-26 02:37:19  Updated

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:

  1. If an AUTO_INCREMENT column exists and the automatically generated values are inserted into the column, the first value is returned.

  2. If LAST_INSERT_ID(expr) is used in a statement, expr is returned, even if an AUTO_INCREMENT column exists.

  3. The return value varies based on the statement used:

    • When you call this function after an INSERT statement, if an AUTO_INCREMENT column 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 ... SELECT statement 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 UPDATE statement, if an AUTO_INCREMENT column 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.

Contact Us