tags:

views:

62

answers:

3

I have an application and around 20 accounts are created per minute (on average). I need to implement a new feature which requires the ID of the last insert.

I am using PDO.

The question is, lets say 5 users create accounts at exactly the same time. Will it return the ID from the database for that users profile that was just created, or will it return the last insert?

If you get what I mean.

A: 

Assuming MySQL (I don´t think all databases have a last-insert ID functionality like MySQL...), every script will return the ID for the item it has just entered, all instances operate independently.

jeroen
Yes MySQL. How does that last-insert-id work then?
James Jeffery
I use `lastInsertId()`, never had any problems with it.
jeroen
+2  A: 

Will it return the ID from the database for that users profile that was just created, or will it return the last insert?

It will return the last insert id of the current connection session. So even if a new record is created in another instance of the same script, the last insert id will be the one you want.

Example (in psuedo-event form):

Create new user // with id of 5

Sleep for 10 seconds - meanwhile another script inserts 3 users

Fetch the last insert id - this will be 5

Mike B
+1  A: 

You should take a look at the PDO::lastInsertID function: http://de.php.net/manual/en/pdo.lastinsertid.php

Kau-Boy
I have looked at this but people are having so many issues with it.
James Jeffery
I use the MySQLi Class and its insert_id (http://de.php.net/manual/en/pdo.lastinsertid.php) function and I never had any problem. As the function works per connection you make through php it will always return the correct id for a user (as long as you execute it in the same script).
Kau-Boy
You can always run a second query getting the new ID using the user data in the WHERE clause if you don't trust the lastInsertId function.
Kau-Boy