views:

106

answers:

1

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.

+3  A: 

PDO::lastInsertId() should work.

EDIT: (did not see your other part)

MySQL mantains the last insert id on a 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).

AlReece45
But as I said in the question, what if several people are adding at the same time. Wouldn't that return an id possibly inserted by someone else? See last line in my question.
dmontain
@dmontain: No. It's per connection. Each request would have its own connection, so this wouldn't be an issue.
ryeguy
@dmontain Added information regarding concurrancy, including a link to the MySQL documentation.
AlReece45