d_biann — 2011-10-21T14:50:52-04:00 — #1
I'm in the process of coding a multi-instance shopping cart and have developed some doubts about the above mentioned functions infallibility:
People will insert the basic information on a product into a "product" table and the primary key will then be fetched with the mentioned function and used as a foreign key for product options in a "prod_options" table affiliated with the data from the product table.
But question is: If another user - almost simultaneously - also inserts into the main "product" table. Could the wrong prod_id then end up being fetched for the first users' prod-options, so a set of product options somehow end up being affiliated with another users' product? If yes, what is the best/most efficient surefire way to prevent this from happening?
Thx for reading.
r937 — 2011-10-21T14:56:17-04:00 — #2
felgall — 2011-10-21T14:57:12-04:00 — #3
No. The id returned is the one relating to the last insert done from your script. It doesn't matter that there have been 50 other inserts in the half second since your insert. That's the whole purpose in using that rather than the maximum value as that maximum is not specific to your insert.
One of the main reasons for that value's existence is to cater for the exact situation you are considering. Any other alternative would suffer from the problems you are concerned about.
d_biann — 2011-10-21T17:09:06-04:00 — #4
Thx for the rapid replies, much appreciated
Well, that's just it. All users will be inserting via the same script. One scipt, handling multiple carts. Do you know how the function operates behind the scenes to quality-ensure the result?
felgall — 2011-10-21T17:51:09-04:00 — #5
No. Each visitor will be running their own iteration of the script. Each execution of the script is separate. Just because there are a hundred copies of the same script running at the same time doesn't mean that things work any differently than if they were a hundred different scripts rather than all of them being copies of the same script.
The values associated with any particular visitor's execution of a script are entirely separate from every other visitor running the same script at the same time. Only when they access information from the database or a file are they looking at the same data.
mysql_insert_id provides a way for each execution of the script to track the value that they inserted into the database regardless of any others that have been inserted since - it provides a field that belongs to the particular execution of the script where simply retrieving the MAX() value from the database would get the last value that was inserted regardless of who inserted it.