插入新行后获取AUTO_INCREMENT值

How can I get the id that was just inserted for the current user if it is controlled by AUTO_INCREMENT?

(I need the Id for another use)

Note: some row can be deleted so MAX(id) is not an option.

Ex:

inserted row 2

inserted row 3

deleted row 3

inserted row 4 but MAX(id) returns 3..

Thank you very much!

With PDO:

$db->lastInsertId(); // $db is the PDO object

With MySQLi OOP:

$db->insert_id; // $db is the MySQLi object

With MySQLi procedural:

mysqli_insert_id($db); // $db is the connection variable

If you're using the old MySQL API, switch.

try

select @@identity

This should return the last value in the identity column

you can use mysql_insert_id

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d
", mysql_insert_id());
?>

EDIT:

mysql_insert_id is deprecated. now its mysqli_insert_id

Since your answer is tagged with PHP, I'll answer in that context. If you're using the PDO API, you can use PDO::lastInsertId. If you're using the mysql function API, the equivalent would be mysqli_insert_id or mysql_insert_id.

Edit: Ninja'd :P

Use mysql_insert_id() or mysqli_insert_id()