note 14579 deleted from function.mysql-insert-id by sander
| From: | sander@php.net | Date: | Sat, 18 May 2002 07:16:34 +0000 |
| Subject: | note 14579 deleted from function.mysql-insert-id by sander | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-30791@lists.php.net to get a copy of this message | ||
Don't we have at problem that MySQL runs at multi threads? This way the LAST_INSERT_ID() may
have been changed before we have the change of getting it...
Here's an example:
1. we do an "INSERT ......."
2. we get the "LAST_INSERT_ID()"
-this example works fine when there is only one user at a time.
BUT - what if this code snippet is to be run by two users starting at the exact same time... this
way the example will look like this:
1. (user 1) do "INSERT"
2. (user 2) do "INSERT"
3. (user 1) get "LAST_INSERT_ID"
4. (user 2) get "LAST_INSERT_ID"
-This way we have at problem, because both users will think that they have inserted the id the user
2 have inserted.
The best solution I came up with was that we have to lock the table for changes betwen the insert
and we gets the id. Some thing like this:
1. lock the table ("LOCK TABLE <table> WRITE")
2. do the "insert"
3. get the "id"
4. unlock the table ("UNLOCK TABLES")
-This way we make sure that nobody else can have made an other inserert and changed the
"last_insert_id" before we have got it.
REMEMBER: If you lock a table it is importend that you unlock it again within the same connection,
or the you can get in trouble. I've even experienced that MySQL will block for all requests or
simply crach. So if you use it, the make sure that you know what you are doing.
Hope these thoughts will help others.