📜  pdo last id - PHP 代码示例

📅  最后修改于: 2022-03-11 14:54:48.489000             🧑  作者: Mango

代码示例2
Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id.



prepare("INSERT INTO test (name, email) VALUES(?,?)");



    try {

        $dbh->beginTransaction();

        $tmt->execute( array('user', 'user@example.com'));

        $dbh->commit();

        print $dbh->lastInsertId();

    } catch(PDOExecption $e) {

        $dbh->rollback();

        print "Error!: " . $e->getMessage() . "
";     } } catch( PDOExecption $e ) {     print "Error!: " . $e->getMessage() . "
"; } ?> When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.