2010-12-05 116 views
6

可能重複:
PHP: how to get last inserted ID of a table?如何獲得一排我剛剛插入的PHP的ID/MySQL的

我正在寫一個函數來添加數據做一個數據庫,但是我想立即在我的代碼中使用該條目。

我知道我可以查詢:SELECT ID FROM表ORDER BY ID DESC

但我不知道是否有這樣做的任何更直接的方式。

+0

您可能想看看我之前爲相關問題提供的示例:http://stackoverflow.com/questions/4358531/mysql-insert-id-does-not-return-the-last-inserted -id-when-i-place-in-a-functi/4358609#4358609 – Mike 2010-12-05 19:39:18

回答

13

這主要取決於你用來訪問MySQL的接口。

如果你使用PDO(推薦),你會使用PDO::lastInsertId()http://us.php.net/manual/en/pdo.lastinsertid.php

如果你使用MySQL,你如果你使用的MySQLi會使用mysql_insert_id()http://php.net/manual/en/function.mysql-insert-id.php

,你'使用mysqli_insert_id()http://us.php.net/manual/en/mysqli.insert-id.php

只需在INSERT完成後立即調用適合的函數即可。

重要的是要注意,您可能不要想要使用SELECT從數據庫中提取id,因爲如果您有多個編寫器,您可能會得到某個其他線程插入的編號。充其量,你會操作錯誤的數據,最糟糕的是,你可能會遇到嚴重的安全問題和/或損壞。

+2

+1可能不是第一個,但它是最全面的。 :-) – 2010-12-05 19:43:21

3
select last_insert_id(); 

Doc

相關問題