Form Receive in 2 different tables

Asked

Viewed 117 times

-1

I have this code to receive data on two different tables. But only the first table is receiving data. The second table is still blank. It is possible for this code to work this way?

if(($query=mysql_query($sqlinsert)) and ($query2=mysql_query($sqlinsert2))){
$sqlinsert = "INSERT INTO tb_funcoes VALUES(0,'"....)";     
$sqlinsert2 = "INSERT INTO tb_detalhe_trabalhador VALUES(0,NULL,NULL,'o."',....)";

}

When the error occurs, returns the following message:

Duplicate entry '0' for key 'PRIMARY'
  • The second query returns error? you better take both mysql_query if and add or die(mysql_error()) in the end. Beware also of andand && because they both have different priorities Logical operators

  • Strange this check. The rest of your code should make sense of this test. But recommend for an OR DIE at the end of each query and read the return.

  • If the first query is being successfully executed, it means that the condition is being valid. The SQL of your second query is exactly this?

  • $sqlinsert and $sqlinsert2should not be before the if ?

  • Exactly. I copied the old code. the $sqlinsert and $sqlinsert2 are before the if

  • @user3253195, tried one query at a time? which error message returned?

  • "If(($query=mysql_query($sqlinsert)) and ($query2=mysql_query($sqlinsert2))){ }" ())"

  • thus without the if, mysql_query('select.....') or die(mysql_error());

  • Duplicate entry '0' for key 'PRIMARY'

Show 4 more comments

1 answer

1

Problem occurs because there is already an id 0 as primary key in your table, so it does not allow you to enter another equal, because primary keys cannot be duplicated, to solve you would have to do the following:

if(($query=mysql_query($sqlinsert)) and ($query2=mysql_query($sqlinsert2))){
  $sqlmax = "select max(nomedocampoID) from tb_funcoes";
  $sqlmax2 = "select max(nomedocampoID) from tb_detalhe_trabalhador";
  $sqlinsert = "INSERT INTO tb_funcoes VALUES(".$sqlmax.",'"....)";     
  $sqlinsert2 = "INSERT INTO tb_detalhe_trabalhador VALUES(".$sqlmax2.",NULL,NULL,'o."',....)";
}

It would be nothing more than taking the last ID(Primary Key) that exists in your tables, so that no ID is duplicated and always auto incrementing.

Note: do not forget to take the name of the field that contains the ID(primary key) and replace it with my "fieldName" I put above.

Browser other questions tagged

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