Reputation: 305
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
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
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
Reputation: 9303
PDO::lastInsertId. Returns the ID of the last inserted row or sequence value
Upvotes: 3