简体   繁体   English

在PHP中使用PDO时,如何检索最后插入的行的ID?

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

Example: I insert a row into the DB with this, using PHP's built in PDO: 示例:使用PHP内置的PDO,我以此向数据库中插入一行:

$sql = "INSERT INTO mytable (name, ok) VALUES ('john', '1')";
$this->dbh->exec($sql);

I need the id of that row. 我需要该行的ID。 How could I get that? 我怎么能得到呢?

If the id is an auto_increment , you can use PDO::lastInsertId : 如果idauto_increment ,则可以使用PDO::lastInsertId

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. 根据基础驱动程序,返回最后插入的行的ID或序列对象的最后一个值。


So, in your case, something like this should do the trick : 因此,在您的情况下,类似这样的方法应该可以解决问题:

$lastId = $this->dbh->lastInsertId();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM