pondpad
pondpad

Reputation: 743

Getting insert id with insert PDO MySQL

Im getting to grips with the basics of PDO.

However Im trying to get the id of the inserted row, Im using:

$query = $system->db->prepare("INSERT INTO {$this->_table} (name,description) VALUES (:name,:description)");
$query->execute(array('name'=>$name,'description'=>$description));

The tutorials I have come across are regarding transactions, however I am not using transactions!

Upvotes: 18

Views: 25064

Answers (2)

Daniel Miranda
Daniel Miranda

Reputation: 111

Pay attention when using transactions.

If you call lastInsertedId after you call commit, lastInsertedId will return 0 instead of the id. Call lastInsertedId right after execute, but before commit.

$this->db->beginTransaction();
$this->stmt->execute();
$id = $this->db->lastInsertId();
$this->db->commit();

Upvotes: 10

Fanis Hatzidakis
Fanis Hatzidakis

Reputation: 5340

You're probably looking for lastInsertId. "Returns the ID of the last inserted row or sequence value".

$insertedId = $system->db->lastInsertId() ;

Upvotes: 33

Related Questions