Get the Unique ID for the Last Inserted Row
by Sanju[ Edit ] 2010-03-04 14:55:37
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.
Example:
We have two tables namely trans and subscribe.
Tables:
create table trans (id BIGINT NOT NULL UNIQUE AUTO_INCREMENT, name VARCHAR(50), amount FLOAT(10,2))
create table subscribe (id BIGINT NOT NULL UNIQUE AUTO_INCREMENT, deducted FLOAT(10,2), transid INT(11))
If you want to insert an id of the table trans that contains an AUTO_INCREMENT column, to the table subscribe in the transid column do use the below insert code,
insert into subscribe values('','$amount', LAST_INSERT_ID())
Here, LAST_INSERT_ID() will insert the id of trans which contains AUTO_INCREMENT.
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().