简体   繁体   English

PDO最后插入ID

[英]PDO Last insert ID

I am using $insertedId = $pdo_conn->lastInsertId(); 我正在使用$insertedId = $pdo_conn->lastInsertId(); to get the last inserted ID after an insert query then i run another insert query: 在插入查询后获取最后插入的ID,然后运行另一个插入查询:

foreach ($records as $emails_to) {
    $stmt = $pdo_conn->prepare("INSERT into emails_to (email_seq, email) values (:email_seq, :email) ");
    $stmt->execute(array(':email_seq' => $InsertedId, ':email' => $emails_to["email"]));
}

but it doesn't seem to recognise the last insert ID, i get this error: 但它似乎无法识别最后一个插入ID,但出现此错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'email_seq' cannot be null'

what have i done wrong? 我做错了什么?

$insertedId and $InsertedId are not the same. $insertedId$InsertedId不相同。 Variable names are case-sensitive. 变量名称区分大小写。

Your $insertedID doesn't match $InsertedID - case issue 您的$insertedID$InsertedID不匹配-大小写问题

edit; 编辑; darn, beaten to the post 该死,被殴打

Beware of lastInsertId() when working with transactions in mysql. 在mysql中处理事务时要当心lastInsertId()。 The following code returns 0 instead of the insert id. 以下代码返回0而不是插入ID。 This is an example 这是一个例子

<?php 
try { 
    $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); 

    $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)"); 

    try { 
        $dbh->beginTransaction(); 
        $stmt->execute( array('user', 'user@example.com')); 
        $dbh->commit(); 
        print $dbh->lastInsertId(); 
    } 
    catch(PDOException $e) { 
        $dbh->rollback(); 
        print "Error!: " . $e->getMessage() . "</br>"; 
    } 
} 
catch( PDOException $e ) { 
    print "Error!: " . $e->getMessage() . "</br>"; 
} 

?> ?>

When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned. 如果未引发任何异常,则lastInsertId返回0。但是,如果在调用commit之前调用了lastInsertId,则会返回正确的ID。

for more informations visit -> PHP 有关更多信息,请访问-> PHP

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

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