user3223205
user3223205

Reputation:

PDO Last insert ID

I am using $insertedId = $pdo_conn->lastInsertId(); to get the last inserted ID after an insert query then i run another insert query:

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:

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

what have i done wrong?

Upvotes: 1

Views: 4531

Answers (3)

iHadaj
iHadaj

Reputation: 475

Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert 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', '[email protected]')); 
        $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.

for more informations visit -> PHP

Upvotes: 3

karlbarbour
karlbarbour

Reputation: 352

Your $insertedID doesn't match $InsertedID - case issue

edit; darn, beaten to the post

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

$insertedId and $InsertedId are not the same. Variable names are case-sensitive.

Upvotes: 6

Related Questions