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 = mysqli_query($link, "INSERT INTO `table` VALUES (NULL, 1005, 'secret');");
$id = mysqli_insert_id($link);
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 yet.