PHP mysql_insert_id() 函數
定義和用法
mysql_insert_id() 函數返回上一步 INSERT 操作產生的 ID。
如果上一查詢沒有產生 AUTO_INCREMENT 的 ID,則 mysql_insert_id() 返回 0。
語法
mysql_insert_id(connection)
參數 | 描述 |
---|---|
connection | 可選。規定 MySQL 連接。如果未規定,則使用上一個連接。 |
說明
mysql_insert_id() 返回給定的 connection 中上一步 INSERT 查詢中產生的 AUTO_INCREMENT 的 ID 號。如果沒有指定 connection ,則使用上一個打開的連接。
提示和注釋
注釋:如果需要保存該值以后使用,要確保在產生了值的查詢之后立即調用 mysql_insert_id()。
實例
<?php $con = mysql_connect("localhost", "hello", "321"); if (!$con) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db("test_db",$con); $sql = "INSERT INTO person VALUES ('Carter','Thomas','Beijing')"; $result = mysql_query($sql,$con); echo "ID of last inserted record is: " . mysql_insert_id(); mysql_close($con); ?>
輸出類似:
ID of last inserted record is: 5