Thread safe way to get auto incremented primary key inserted into another table (so they can be joined later)

StackOverflow https://stackoverflow.com/questions/7780533

  •  10-02-2021
  •  | 
  •  

Domanda

It seems there are two methods for this, the first one goes like this:

$result = mysql_query("SHOW TABLE STATUS LIKE 'table_name'");
$row = mysql_fetch_array($result);
$nextId = $row['Auto_increment'];
mysql_free_result($result);

$sql = mysql_query("INSERT the information you want in the main table")

You can then insert $nextid as a foreign key in all your related tables.

The other method uses last insert id:

START TRANSACTION;
INSERT INTO files (file_id, url) VALUES (NULL, 'text.doc');
INSERT INTO grades (file_id, grade) VALUES (LAST_INSERT_ID(), 'some-grade');
COMMIT;

Are both of these thread safe? IE, if I have two php scripts running two mysql threads at the same time and they insert into the main table at the same time will the associated tables receive the correct primary id foreign key or could there be a mixup or collision?

Thanks.

È stato utile?

Soluzione

Use the second (or mysql_insert_id()) as it is multi-user safe anyway. The transaction is only needed for consistency reasons but not for the LAST_INSERT_ID(). Furthermore, you should use mysqli_*() instead of mysql_*() as it is the improved database access library.

Altri suggerimenti

The last one is better, using INSERTED_ID! The other option is also ok, but it could be that if you have more people using the same page, it will go wrong.

Although that is very unlikely.

I think a trigger with last_insert_ID() to insure the code is fired immediately after an insert operation is the best approach, assuming you want this to happen after every insert.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top