简体   繁体   中英

Get the AUTO_INCREMENT value after inserting a new row

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

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

使用mysql_insert_id()或mysqli_insert_id()

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\n", mysql_insert_id());
?>

EDIT:

mysql_insert_id is deprecated. now its mysqli_insert_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM