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

Asked

Viewed 11,274 times

5

I need to make an insertion as follows:

I have two tables TABELA 1 and TABELA 2 and a cadre form.
This form has three inputs: input 1, input 2, input 3
The input 1 shall be inserted into TABELA 1.
The input 2 e input 3 need to be inserted into the TABELA 2
However TABELA 2 has a foreign key field of the TABELA 1 which is the foreign key to input 1.
I need to make sure that by submit form fields are saved in the tables and the foreign key field of the TABELA 2 receive the ID of the new insert that was made in TABELA 1.

1 answer

6


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

Mysql source
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 );
  • 1

    Thank you very much Thiago I’ll be and as soon as I test I’ll be back to mark your reply :) Thanks again

  • I don’t know what happened but the second Query does not execute, the first query runs normally and the name is saved correctly in the database in its table, but the data of the second INSERT is not written.

  • 1

    Do this, comment on the line mysql_query( $query2 ); and gives a echo in the variable $query2, then put the result here.

  • I made some changes to the code and it worked perfectly the error was in my code Thank you very much Thiago!

  • Very good, I managed to solve my problem thanks to your tip. .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.