How to retrieve the id of the last inserted row when using PDO in PHP?

天大地大妈咪最大 提交于 2020-01-09 12:08:32

问题


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);

I need the id of that row. How could I get that?


回答1:


If the id is an auto_increment, you can use PDO::lastInsertId :

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();


来源:https://stackoverflow.com/questions/1961471/how-to-retrieve-the-id-of-the-last-inserted-row-when-using-pdo-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!