Name

mysql_insert_id —

Synopsis

my_ulonglong mysql_insert_id(MYSQL *mysql)

Returns the generated value for an AUTO_INCREMENT field if the last query created a new row. This function is usually called immediately after a value has been inserted into an AUTO_INCREMENT field to determine the value that was inserted. This value is reset to 0 after any query that does not insert a new auto-increment row.

Tip

The MySQL-specific SQL function LAST_INSERT_ID( ) also returns the value of the most recent auto-increment. In addition, it is not reset after each query, so it can be called at any time to retrieve that value of the last auto-increment INSERT executed during the current session.

Example

/* We just inserted an employee record with automatically generated ID into
   a table */
id = mysql_insert_id(&mysql);
printf("The new employee has ID %d\n", id);
/* As soon as we run another query, mysql_insert_id will return 0 */

Get Managing & Using MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.