Insert data Database Related tables

Asked

Viewed 1,619 times

1

I’m having trouble inserting data that has related tables.

$sqlinsert2 = "INSERT INTO tb_detalhe_trabalhador VALUES(0,NULL,NULL,'".$MedicaValidade."',..

Currently the data that are as NULL are the fields related to the Table.

tb_details_worker:

`id` int(11) NOT NULL AUTO_INCREMENT,
`tb_trabalhador_id` int(11) DEFAULT NULL,
`tb_funcoes_id` int(11) DEFAULT NULL,
`MedicaValidade` date DEFAULT NULL,
`MedicaAnexo` longblob,
 (...)
  • It is difficult to answer your question without having the DDL of the tables. You can edit your question with the same?

3 answers

2

There is a resource called mysql_insert_id() which will return the insert key, assign this resource to a variable and then insert it again in the related table.

2

From what I understand you are not able to insert the data in the table tb_detail_worker because it has two Foreign key (tb_worked id, tb_functions_id) so it will not be possible because even with default null it must be linked to the reference tables, or it may be because of the zero value (0) as id of the detail tb_worker you are inserting that it is not possible, so in this case, for being an autoincrement field it is not necessary to pass any value.

  • I don’t think the problem is NULL keys. For me the problem is in the table id (value zero).

  • I just did a local test and saw that it accepts null value even related to another table if it is with DEFAULT NULL like this one, and also accepts the (zero value) and still does the Insert with auto increment. Does it have something else that has beyond the difficulty in inserting, because what a mistake this giving?

  • There is no error. But when I see the data tb_worker_id is null. I cannot do INNER JOIN

  • @user3253195 now I do not understand. Because in the Insert that showed this inserting the value as NULL and so will not have relation anyway, so when doing INNER JOIN has no relation, but if you still need to appear in your query try to use a LEFT|RIGHT JOIN. (or try to improve your doubt)

  • But the problem with Left/Right Join is that it only shows me one of the tables. E with INNER Join the result is blank

  • Come on, your problem is insert or in the select? If it is in the insert just review everything that has been said and possibly improve your question, but if it is in the select, has no relationship to tabelaA with the tabelaB where the field that makes this relation is with NULL value, understood?

Show 1 more comment

2

You must have tb_trabalhador_id already recorded in the related table before making this query or it will give error. In addition, the value of tb_trabalhador_id must be exactly the same as in the related table.

NOTE: Your question is related to Database friend, and not to PHP or Insert (Mysql or SQL would be better).

Browser other questions tagged

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