Skip to content
Advertisement

Getting the record ID just added with mysql prepared statements

I’m inserting a record using PDO and saving the result in $result which I use as a boolean

$result = $addRecord->execute();

if ($result){ 
   //add successful
} else {
   //add unsuccessful
}

I’d like to also get the record id just added. In the table, each record has an auto_incremented field called id. I tried doing this

$new_id = $result['id'];

but it seems $result doesn’t actually hold the record added. Can someone confirm this and how would I then access the record just added?

Note that several people may be adding to the same table at the same time, so I need something really accurate.

Advertisement

Answer

PDO::lastInsertId() should work.

EDIT: (did not see your other part)

MySQL mantains the last insert id on a http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html”>per-connnection basis. So if something else inserts a row it should only return unexpected results if that query was executed using the same connection (like a persistent connection).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement