Q:

PHP/MySQL Get autoincremented value after insert

In my mysql table i have an id-column which is set to autoincrement.
then i do queries like this:
INSERT INTO table (id, foo) VALUES ('', 'bar')
how can i then safely find out which id was generated with this insert?
if i just query the last id this might not be safe, since another insert could have happened in the meantime, right?

A:

There's a PHP and also a MySQL function for this: mysqli_insert_id() and PDO::lastInsertId().
http://php.net/manual/en/function.mysql-insert-id.php

A:

Use  LAST_INSERT_ID() in SQL
    SELECT LAST_INSERT_ID();

Use  mysql_insert_id() in PHP

A:

If you are using PHP to get the auto_incremented value that is returned after an INSERT statement, try using the MySQLi insert_id function.  The older mysql_insert_id() version is being deprecated in PHP.
An example below:
 <?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* drop table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

