简体   繁体   中英

Getting the last inserted row after doing an INSERT in PDO (with MySQL)?

when inserting a new object (as a row) into the MySQL database I want to get the last inserted row back (id is NOT always enough, as I want to use this in a generic functions where some INSERTs do not have any auto-incremented IDs).

I need this to give the full object back on success with POSSIBLY database-created id, timestamp, or in some cases just the values I knew before inserting - so PDO::lastInsertId does not solve the problem.

$query = "INSERT INTO table (".$colinsert.") VALUES (".$colbind.")";
$stmt = $this->db->prepare($query);
$ex = $stmt->execute();
// ... if $ex was successful, how do I retrieve the last inserted row now?

A database-independent solution would be nice, but if it is MySQL specific it is also ok :-)

Edit: To prevent some misunderstandings - eg I have the table user_contact_connection with the following rows (contact_id,user_id,additional_connection_info). The primary key is (contact_id,user_id). PDO::lastInsertId returns 0 in this case, as there is no auto increment column.

Ok in this case I KNOW which row I have been inserting, however I still hope to find a way to just get the last inserted row generically WITHOUT explicitly querying for the IDs? Is this even possible?

If you want to use an object after persisting in the db and you want the object to have the values that your db calculates (eg. have the default values back that you don't provide with the insert statement, get the timestamps resulting from MySQL NOW(), etc.), probably the best is fetching after insert. However, using some ORM library like Doctrine, you could construct the object with all the values before persisting but then you have to provide defaults, timestamps, etc. (autoincrement must be fetched anyway).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM