When INSERTing a record into a MySQL table it is sometimes useful to get the index (id) of that record which was calculated by auto_increment. Here is a fail-safe, guaranteed way of doing it:
In PHP:
$result = mysql_query("INSERT INTO `table` VALUES (NULL, 1005, 'secret');"); $id = mysql_insert_id();
This PHP function simply calls the MySQL function: “SELECT LAST_INSERT_ID()”
NOTE: If you use the SELECT… query instead of the PHP function then never include a FROM clause to specify the table (or any table), it will return the last id multiplied by the number of records in the table.
ALSO NOTE: Don’t query the Database and try to find the highest id, as this may belong to someone else INSERTing into the same table.





Discussion
No comments for “Get the index (‘id’) from the most recently inserted record in MySQL using PHP”