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

Example: I insert a row into the database with this using PHP built into PDO:

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

I need the id of this string. How can i get this?

0
source share
1 answer

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

Returns the identifier of the last inserted row or the last value from the sequence of the object, depending on the driver.


So, in your case, something like this should do the trick:

 $lastId = $this->dbh->lastInsertId(); 
+3
source

Source: https://habr.com/ru/post/1415544/


All Articles