I made a function that inserts a new line into a table, after calling an INSERT
statement into mysql, I then make some checks, and then I check the value of mysql_insert_id()
.
I want to be quiet knowing that it is not possible for another thread to break in, inserting a row, before I get the result of mysql_insert_id()
.
My bet is that it should be safe, but I am asking because this one can be disastrous.
From the manual
:
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.
So if your threads will use separate connections, they will get different insert IDs.
Yes you can. If mysql_insert_id() could be affected by other almost simultaneous hits to the same PHP script it would be useless.
It works on a per-connection basis.
来源:https://stackoverflow.com/questions/25505200/can-i-trust-mysql-insert-id-to-return-correct-value-multithreading-paranoia