Bala
Bala

Reputation: 3638

How to get exactly the id of the last inserted record in mysql?

I am building a web application, which can be used by multiple users simultaneously. They can add data at the same time.

I have a table named doctor_main as follows

Screenshot of DB http://img687.imageshack.us/img687/7033/testxqz.png

Once a record about a doctor is added, I want the id of the inserted record(which is an auto increment field) to be returned.

I know i can use methods like LAST_INSERT_ID() and mysql_insert_id. But i don't know how it behaves.

I need the exact id of the record which is inserted by that particular user.

Sometimes, if two users are trying to insert a record, the id which is returned shouldn't get exchanged.

To achieve this what kind of mysql function should i use ?

Upvotes: 3

Views: 2604

Answers (6)

kays
kays

Reputation: 1

If you are suspicious on the mechanism of last_insert_id, then you may assign the id by hand not by auto_increment feature of MySQL.

Upvotes: -1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

LAST_INSERT_ID() and mysql_insert_id works fine. Each client will receive the last inserted ID for the last statement that client executed.

Upvotes: 2

Gary Chambers
Gary Chambers

Reputation: 25828

LAST_INSERT_ID() operates per-connection; multiple users will use multiple connections, so there will never be an exchange of IDs between users.

Upvotes: 2

Simone
Simone

Reputation: 21262

mysql_insert_id() returns exactly the id of the last inserted record, so if you just echo mysql_insert_id() you'll get the id of the very last inserted row.

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 837946

There's a whole page in the manual dedicated to this subject:

Here's a quote from that page that should help answer your question:

For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client.

Upvotes: 8

user800014
user800014

Reputation:

According to the docs, the mysql_insert_id will return to you the exact id of the insert that you done before.

Upvotes: 2

Related Questions