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!
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.
If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.
You're probably looking for lastInsertId. "Returns the ID of the last inserted row or sequence value".
$insertedId = $system->db->lastInsertId() ;
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With