简体   繁体   English

插入新行后获取AUTO_INCREMENT值

[英]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 ? 如果它是由AUTO_INCREMENT控制的,如何获取刚刚为当前用户插入的id

(I need the Id for another use) (我需要该ID供其他用途)

Note: some row can be deleted so MAX(id) is not an option. 注意:可以删除某些行,因此不能选择MAX(id)

Ex: 例如:

inserted row 2 插入第2行

inserted row 3 插入第3行

deleted row 3 删除第3行

inserted row 4 but MAX(id) returns 3.. 插入第4行,但MAX(id)返回3。

Thank you very much! 非常感谢你!

With PDO: 使用PDO:

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

With MySQLi OOP: 使用MySQLi OOP:

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

With MySQLi procedural: 使用MySQLi程序:

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

If you're using the old MySQL API, switch. 如果您使用的是旧版MySQL API,请切换。

try 尝试

select @@identity 选择@@ identity

This should return the last value in the identity column 这应该返回标识列中的最后一个值

Since your answer is tagged with PHP, I'll answer in that context. 由于您的答案是用PHP标记的,因此我将在这种情况下回答。 If you're using the PDO API, you can use PDO::lastInsertId . 如果您使用的是PDO API,则可以使用PDO :: lastInsertId If you're using the mysql function API, the equivalent would be mysqli_insert_id or mysql_insert_id . 如果您使用的是mysql函数API,则等价于mysqli_insert_idmysql_insert_id

Edit: Ninja'd :P 编辑:忍者:P

使用mysql_insert_id()或mysqli_insert_id()

you can use mysql_insert_id 您可以使用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. mysql_insert_id已过时。 now its mysqli_insert_id 现在它的mysqli_insert_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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