mysql_insert_id

(PHP 4, PHP 5)

mysql_insert_id 取得上一步 INSERT 操作產(chǎn)生的 ID

說明

mysql_insert_id(resource $link_identifier = ?): int

mysql_insert_id() 返回給定的 link_identifier 中上一步 INSERT 查詢中產(chǎn)生的 AUTO_INCREMENT 的 ID 號。如果沒有指定 link_identifier,則使用上一個打開的連接。

如果上一查詢沒有產(chǎn)生 AUTO_INCREMENT 的值,則 mysql_insert_id() 返回 0。如果需要保存該值以后使用,要確保在產(chǎn)生了值的查詢之后立即調(diào)用 mysql_insert_id()

注意:

MySQL 中的 SQL 函數(shù) LAST_INSERT_ID() 總是保存著最新產(chǎn)生的 AUTO_INCREMENT 值,并且不會在查詢語句之間被重置。

警告

mysql_insert_id() 將 MySQL 內(nèi)部的 C API 函數(shù) mysql_insert_id() 的返回值轉(zhuǎn)換成 long(PHP 中命名為 int)。如果 AUTO_INCREMENT 的列的類型是 BIGINT,則 mysql_insert_id() 返回的值將不正確??梢栽?SQL 查詢中用 MySQL 內(nèi)部的 SQL 函數(shù) LAST_INSERT_ID() 來替代。

示例 #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 %d\n"mysql_insert_id());
?>

參見 mysql_query()。