(PHP 4, PHP 5)
mysql_insert_id — 取得上一步 INSERT 操作產生的 ID
說明
int mysql_insert_id ([ resource$link_identifier
] )
mysql_insert_id()
返回給定的
link_identifier
中上一步 INSERT 查詢中產生的 AUTO_INCREMENT 的 ID 號。如果沒有指定
link_identifier
,則使用上一個打開的連接。
如果上一查詢沒有產生 AUTO_INCREMENT 的值,則 mysql_insert_id() 返回 0。如果需要保存該值以后使用,要確保在產生了值的查詢之后立即調用 mysql_insert_id()。
Note:
MySQL 中的 SQL 函數 LAST_INSERT_ID() 總是保存著最新產生的 AUTO_INCREMENT 值,并且不會在查詢語句之間被重置。
Warningmysql_insert_id() 將 MySQL 內部的 C API 函數 mysql_insert_id() 的返回值轉換成 long(PHP 中命名為 int)。如果 AUTO_INCREMENT 的列的類型是 BIGINT,則 mysql_insert_id() 返回的值將不正確。可以在 SQL 查詢中用 MySQL 內部的 SQL 函數 LAST_INSERT_ID() 來替代。
Example #1 mysql_insert_id() 例子
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf ("Last inserted record has id %dn", mysql_insert_id());
?>
參見 mysql_query()。