简体   繁体   中英

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 ?

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.

mysql_insert_id()完全返回最后插入记录的id,所以如果你只是echo mysql_insert_id()你将得到最后一个插入行的id。

根据文档mysql_insert_id将返回您之前完成的插入的确切ID。

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

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

如果您对last_insert_id的机制持怀疑last_insert_id ,那么您可以手动分配id而不是MySQL的auto_increment功能。

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