[英]Get the AUTO_INCREMENT value after inserting a new row
如果它是由AUTO_INCREMENT
控制的,如何獲取剛剛為當前用戶插入的id
?
(我需要該ID供其他用途)
注意:可以刪除某些行,因此不能選擇MAX(id)
。
例如:
插入第2行
插入第3行
刪除第3行
插入第4行,但MAX(id)
返回3。
非常感謝你!
使用PDO:
$db->lastInsertId(); // $db is the PDO object
使用MySQLi OOP:
$db->insert_id; // $db is the MySQLi object
使用MySQLi程序:
mysqli_insert_id($db); // $db is the connection variable
如果您使用的是舊版MySQL API,請切換。
嘗試
選擇@@ identity
這應該返回標識列中的最后一個值
由於您的答案是用PHP標記的,因此我將在這種情況下回答。 如果您使用的是PDO API,則可以使用PDO :: lastInsertId 。 如果您使用的是mysql函數API,則等價於mysqli_insert_id或mysql_insert_id 。
編輯:忍者:P
使用mysql_insert_id()或mysqli_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());
?>
編輯:
mysql_insert_id已過時。 現在它的mysqli_insert_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.