Mysql – Using the auto increment id from one query as the fk of the next insert

auto-incrementinsertMySQLPHPtransaction

I'm not sure if I'm overcomplicating this or whether I can't see the wood for the trees.

I have two tables, both have auto incrementing ID's.

Table 1:
ID - auto
field - int
other field - varchar

Table 2:
ID - auto
Table1Id - FK
field - varchar

the first table stores an article and the 2nd stores the location of the images related to it.

For my form that uploads the data all information to be stored is taken. I need to run two inserts simultaneously (which I realise is daft) using the same ID.

My plan(flawed) is to insert into table 1, get the id and then insert into table 2.

one of the problems if is a user accesses the site in the gap between the two inserts and sees a mess.

is there an easier way, I think I've made a mistake or I'm missing something obvious as it shouldn't be this difficult. 🙂

Best Answer

This is (in part) where transactions come in. Assuming your transaction isolation level is "read committed", "repeatable read" or "serializable" (MySQL defaults to "Repeatable read" and anyone setting it to lower than "read committed" is committing crimes against the laws of the universe), other transaction are blind (to some extent) to changes made within your transaction.

So you should:

START TRANSACTION;
INSERT #1;
INSERT #2;
COMMIT;

The other transactions will not be able to read your first INSERTed row (though they can find trace of its existence via locks -- probably not interesting to you). They will only be able to read both your changes or none of them.

This, again, depends on the assumption that these transactions don't come from a connection with "Read committed" isolation level -- which, unfortunately -- is something anyone is able to change for their own connection.