In the users table I am adding new rows, these rows need to each contain a reference the id of a unique row in another “access keys” table.
Some of these users rows may be added simultaneously from many threads. I know these will be database blocking with the writes so not truly simultaneously. So maybe this is not a concern?
So I have a php script that creates the new user row, and I have the access keys table populated with many rows. How do I generate the reference to the id of a unique row in the “access keys” table and how do I know it is unique?
You do it sequentially from whatever thread(s) are doing the insertion:
1) add row to the users table
2) retrieve ID of this new row
3) insert into access keys table using the ID retrieved in #2
4) go to 1) until completed
MySQL can securely return the last ID it created as part of an insert query for each connection – an insert done by some OTHER thread will not overwrite another thread’s “last insert id” – the last insert id kept on a per-connection basis.
With this structure, you can have as many threads as you want doing inserts, and none of them will step on each other’s toes, as they’re all getting their own distinct “last id”.