How to insert data into two tables at the same time?

5

I need to do an insert as follows:

I have two tables TABELA 1 and TABELA 2 and a form of cadatro. This form has three inputs: input 1, input 2, input 3
input 1 must be entered in TABELA 1 . input 2 e input 3 need to be entered in TABELA 2
However, TABELA 2 has a foreign key field of TABELA 1 which is the foreign key of input 1 .
I need to make that when doing the submit of the form the fields are written to the tables and the foreign key field of TABELA 2 receives the ID of the new insert that was made in TABELA 1 .     

asked by anonymous 12.03.2015 / 16:15

1 answer

6

You can use the mysql_insert_id function for MySQL or the mysqli_insert_id function for MySQLi

MySQL Font
MySQLi Font

For example:

$query1 = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query1 );

$id = mysql_insert_id();

$query2 = "INSERT INTO test_2 (test_id, value) VALUES ({$id}, 'test')";
mysql_query( $query2 );
    
12.03.2015 / 16:33