本文介紹了在PHP中使用PDO時如何檢索最后插入行的id?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
示例:我使用 PHP 內置的 PDO 將一行插入到數據庫中:
Example: I insert a row into the DB with this, using PHP's built in PDO:
$sql = "INSERT INTO mytable (name, ok) VALUES ('john', '1')";
$this->dbh->exec($sql);
我需要該行的 ID.我怎么能得到它?
I need the id of that row. How could I get that?
推薦答案
如果 id
是 auto_increment
,你可以使用 PDO::lastInsertId
:
If the id
is an auto_increment
, you can use PDO::lastInsertId
:
返回最后插入的ID行,或序列中的最后一個值對象,取決于底層司機.
Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver.
所以,在你的情況下,這樣的事情應該可以解決問題:
So, in your case, something like this should do the trick :
$lastId = $this->dbh->lastInsertId();
這篇關于在PHP中使用PDO時如何檢索最后插入行的id?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!