Sander Mangel
Sander Mangel

Reputation: 305

Getting the insert and update ID with PDO

Im trying to get the mysql_insert_id using PDO. Thus far i've not found a good example that works with both inserting and updating. Does anyone have a piece of complete code as example?

Upvotes: 4

Views: 14312

Answers (3)

Idrees Khan
Idrees Khan

Reputation: 7752

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

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

    try { 
        $dbh->beginTransaction(); 
        $stmt->execute( array('user', '[email protected]')); 
        $dbh->commit(); 
        print $dbh->lastInsertId(); 
    } catch(PDOExecption $e) { 
        $dbh->rollback(); 
        print "Error!: " . $e->getMessage() . "</br>"; 
    } 
} catch(PDOExecption $e) { 
    print "Error!: " . $e->getMessage() . "</br>"; 
} 
?>

Upvotes: 0

Wrikken
Wrikken

Reputation: 70490

If you need $pdo->lastInsertId() to return the id of the row just updated (I would seriously reconsider my design if I needed it but hey... can be a true need), do the update like this:

 UPDATE tablename  SET some_column='somevalue',id=LAST_INSERT_ID(id);

Upvotes: 9

W Kristianto
W Kristianto

Reputation: 9303

PDO::lastInsertId. Returns the ID of the last inserted row or sequence value

Upvotes: 3

Related Questions