Insert_ID()\"" />
开发者

how do i handle concurrent inserts in mysql table and fetch the correct insert id

开发者 https://www.devze.com 2022-12-18 09:07 出处:网络
I am using adodb for PHP library. For fetching the id at which the record is inserted I use this function \"$db->Insert_ID()\"

I am using adodb for PHP library.

For fetching the id at which the record is inserted I use this function

"$db->Insert_ID()"

I want to know if there are multiple and simultaneous inserts into the database table, will this method return me the correct inserted id for each record inserted ?

The reason I am asking this is because I use this last insert id for further processing of other records and making subsequent entries in the related tables.

Is this approach safe enough or am I missing something.

Please help me formulate a proper working plan for this so that I can use the last insert id for further inserts into the other table safely without开发者_JAVA百科 having to mess up with the existing data.

Thanks


Yes, it's safe for concurent use. That's because LAST_INSERT_ID() is per-connection, as explained here:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.


The $db->Insert_ID() will return you last insert id only so if you are inserting many records and want to get id of each last inserted row, then this will work successfully.


I want to know if there are multiple and simultaneous inserts into the database table, will this method return me the correct inserted id for each record inserted ?

It will return only the most recently inserted id.
In order to get ids for multiple inserts, you will have to call INSERT_ID() after each statement is executed. IE:

INSERT INTO TABLE ....
INSERT_ID()

INSERT INTO TABLE ....
INSERT_ID()

...to get the id value for each insert. If you ran:

INSERT INTO TABLE ....
INSERT INTO TABLE ....
INSERT_ID()

...will only return the id for the last insert statement.

Is this approach safe enough or am I missing something.

It's safer than using SELECT MAX(id) FROM TABLE, which risks returning a value inserted by someone else among other things relating to isolation levels.

0

精彩评论

暂无评论...
验证码 换一张
取 消