Cannot add or update a Child Row

Asked

Viewed 79 times

1

Good, I have these tables with the following structures:

Athletes: id_atletas id_identificacao nome_completo licenca

Identification: id_identificacao nome_pretendido data_nascimento

The id_identification is as FK in the table Athletes and wanted when registering the athlete the Id_identification table Identification increase in the table Athletes.

I have the following code:

$query_identificacao = "INSERT INTO identificacao (nome_pretendido, data_nascimento) VALUES ('$nome_pretendido', '$data_nascimento')";
$id = mysql_insert_id();

$query_atletas = "INSERT INTO atletas (nome_completo, licenca, id_identificacao) VALUES ('$nome_completo', '$licenca', '$id')";
$id = mysql_insert_id(); 

mysql_query($query_identificacao) or die(mysql_error());
mysql_query($query_atletas) or die(mysql_error());

But give me the following mistake:

Cannot add or update a Child Row: a Foreign key Constraint fails (teste.atletas, CONSTRAINT atletas_ibfk_7 FOREIGN KEY (id_identificacao) REFERENCES identificacao (id_identificacao))

  • In the first $id = mysql_insert_id(); a valid value is returned?

1 answer

2

Only after you run the query (with mysql_query()) is that you will be able to get the id inserted (with mysql_insert_id()). Example:

$query_identificacao = "INSERT INTO identificacao (nome_pretendido, data_nascimento) VALUES ('$nome_pretendido', '$data_nascimento')";
mysql_query($query_identificacao) or die(mysql_error());
$id_identificacao = mysql_insert_id();

$query_atletas = "INSERT INTO atletas (nome_completo, licenca, id_identificacao) VALUES ('$nome_completo', '$licenca', '$id_identificacao')";
mysql_query($query_atletas) or die(mysql_error());
$id_atleta = mysql_insert_id(); 

Browser other questions tagged

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