Reputation:
I have two tables in my database 'file' and 'message'. If a user submit a file I first submit the file name in the file table, location and so on in my database. After that I inmedietley set the following variable:
$file_id = mysql_insert_id();
This will get the assigned id of the the file, with that variable I can the insert it into the message table, such as message_file_id. That way I can get message file, with just an id.
All is working, but my question is. If I were to have 2 users submit a message with a file at the same time (which would be hard, or even impossible) is there a possibility user A gets user B file id?
There is variable that could affect this like a user having faster or slower time than another.
Upvotes: 0
Views: 55
Reputation: 2719
No, there is no chance User A will get User B's file ID as long as both transactions were performed in the same connection. MySQL is smart enough to give out distinct auto-increment IDs to different connections, even if they are inserting into the same table concurrently. You don't even have to wrap the two inserts in a transaction.
So there is no problem at all as long as you're using mysql_insert_id() - it will always work as you would expect it to and won't mix up IDs, and you are completely safe to use the return value from mysql_insert_id as a the foreign key in a record related to the one you have just inserted.
http://dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html
Upvotes: 2