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.
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 theLAST_INSERT_ID(). Furthermore, you should usemysqli_*()instead ofmysql_*()as it is the improved database access library.