24.1.4.3 How Can I Get the Unique ID for the Last Inserted
Row?/*********** the following is from manual of MySQL ************/
If you insert a record in a table containing a column that has the AUTO_INCREMENT attribute,you can get the most recently generated ID by calling the mysql_insert_id() function.You can also retrieve the ID by using the LAST_INSERT_ID() function in a query stringthat you pass to mysql_query().You can check if an AUTO_INCREMENT index is used by executing the following code. Thisalso checks if the query was an INSERT with an AUTO_INCREMENT index:if (mysql_error(&mysql)[0] == 0 && mysql_num_fields(result) == 0 && mysql_insert_id(&mysql) != 0) { used_id = mysql_insert_id(&mysql); }
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