How to find last inserted id while using pdo trans

2019-08-30 09:08发布

问题:

I'm using PDO in my web application. In a part of this application, I need to work with PDO Transactions. I need to know last inserted id of first query and use it in the second query, and then if no problem occurs, I will commit this transaction.
The problem I have is that how can I find out last inserted id before transaction commit?
This is a sample of my need :

$db->beginTransaction();  

$stmt1 = "INSERT ...";  // An insert query
$q = $db->prepare($stmt1);  
$q->execute(array());  

$last = $db->lastInsertId();

$stmt2 = "UPDATE ...";  // An update query
$q2 = $db->prepare($stmt2);  
$q2->execute(array($last));  

$db->commit();