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

后端 未结 3 587
栀梦
栀梦 2021-01-06 14:38

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 t

3条回答
  •  滥情空心
    2021-01-06 14:57

    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.

提交回复
热议问题