Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Insert new IDs as Foreign Keys in 2nd tab right after they got written

Problem with writing multiple foreign keys.



3:18 am on Nov 20, 2009 (gmt 0)

5+ Year Member

I am new to PHP, not sure this belongs to PHP or MySQL. Here is my scenario:

I have multiple data from a form search that I want to write to 2 tables. So far that's no problem.

But the incremental IDs (plural!) that are created in TABLE1.ID should be inserted as foreign keys in TABLE2.ID_T1

My first thought was that mysql_insert_id()or last_insert_id() would come in handy - but they just can handle one ID, but I insert several.

Does anybody has clue how to work this out?


5:45 am on Nov 20, 2009 (gmt 0)

10+ Year Member

not sure what you want to do. could you not append each last_insert_id to an array and then do the second batch of inserts?


6:09 am on Nov 20, 2009 (gmt 0)

5+ Year Member

I did a workaround now. I created a new field in TABLE1 and inserted there the source ID. Then I take the incremented TABLE1.ID and put it into TABLE2 as foreign ID. Seems to work.

$sql = "INSERT INTO table1 (field1)VALUES
('" .implode("'), ('", $_POST['checkbox']) . "')";

mysql_query($sql) or exit(mysql_error());

$sql = "INSERT INTO table2 (id_t1)
SELECT table1.id FROM table1
WHERE field1 IN ('" .implode("', '", $_POST['checkbox']) . "') ";



Featured Threads

Hot Threads This Week

Hot Threads This Month