meee — 2011-02-01T08:50:13-05:00 — #1
I am not sure if I understand correctly lock tables statement. I hope somebody can explain this situation:
I would like to lock table photos, so nobody can insert new photo while user A is inserting photo and getting inserted id.
photoId | photo | userId
$db->query("LOCK TABLES photos write");
$db->query("INSERT INTO photos (userId,photo) VALUE (1,'$photo')");
I tried this in localhost. First I removed the last line ($db->query("UNLOCK TABLES")), so when a user A open the script, table stays locked. I opened script test.php in firefox and then the same script as user B in chrome. As user B I didn't get any error and new photo has been inserted. Why that? Isn't supossed to get error in this case as table is still locked?
r937 — 2011-02-01T09:16:45-05:00 — #2
you don't need to do that
mysql_insert_id is guaranteed to get you the correct value for each separate connection
meee — 2011-02-01T09:35:12-05:00 — #3
So there is no chance that another user will in exact the time between insert and mysql_inser_id insert another photo or is it just so small possibility?
But anyway if I or somebody else needs that for other purposes. I think my the problem was that after the php script ends, it also unlock table automatically. Normally lock will means that execution of script will wait for beeing table unlocked, without any error. Am I right?
jurn — 2011-02-01T09:48:29-05:00 — #4
no, the php mysql insert id / auto_increment is guaranteed to be unique, MySQL will handle this internally.
Yes, I think it will be fine in most cases,
BUT what happens if your php script dies right after it 'locks tables'.
and it can also put extra load on the database - mysql will be handle the concurrency around the id generation, but you're making it handle concurrency for the whole table.
meee — 2011-02-05T18:27:58-05:00 — #5
"But there’s a slight window of opportunity for an error to slip in. Suppose that two
people visit the website at the same time and submit new information, causing the web
server to run your program twice at the same time. (Web servers can run several programs
at the same time to speed up response time.) The second visitor might insert a
new cat just before the first visitor’s program issues mysql_insert_id. This is a rare but
serious problem, because the first person could end up being associated with the second
So a completely safe procedure for linking tables through the insert ID is to use locks"
jurn — 2011-02-06T18:22:03-05:00 — #6
I acquired the book because you made me worry
The author gracefully admits to a mistake.
r937 — 2011-02-06T18:44:07-05:00 — #7
jurn, awesome update, thanks for that
in any dispute between the vendor's docs and a book, i would go with the docs
you're right, that was a graceful admission