How to insert in a related table

0
<?php
## Título ##
if ($_POST) {
    $nombre = $_POST['nombre'];
    $apellido = $_POST['apellido'];
    $identidad = $_POST['identidad'];
    $edad = $_POST['edad'];
    $sexo = $_POST['sexo'];
    $hijos = $_POST['hijos'];
    $telefono = $_POST['telefono'];
     $municipios = $_POST['municipios'];//*este es un select de otra tabla municipios que me muestra todos los municipios *//

$ lastvalue = $ municipalities; // * here I get the value of the select to be able to insert it so that it has the same id as person * //

    $conexion = mysqli_connect("127.0.0.1", "root", "", "persona_municipio");
    $ultimovalor=mysqli_insert_id($conexion);

    if ($conexion->connect_error) {
        echo('Se produjo un error al intentar realizar la conexión');
    } else {
        $query = "INSERT INTO persona(nombre,apellido,identidad,edad,sexo,hijos,telefono,id_municipio)
        VALUES ('$nombre','$apellido','$identidad','$edad','$sexo','$hijos','$telefono','$ultimovalor')";

        if ($conexion->query($query) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $query . "<br>" . $conexion->error;
        }
        $conexion->close();
    };    
};
?>

Error:

  

INSERT INTO   person (name, surname, identity, age, sex, children, telephone, id_municipality)   VALUES ('juan', 'veliz', '1517199600702', '22', 'm', '3', '96453034', '0')   Can not add or update to child row: a foreign key constraint fails   (person_municipality.person, CONSTRAINT persona_ibfk_1 FOREIGN KEY   (municipality_id) REFERENCES municipality (municipality_id) ON DELETE CASCADE   ON UPDATE CASCADE)

    
asked by user9472850 06.07.2018 в 19:49
source

1 answer

0

One of the most common causes when you get an error in Mysql of the type:

  

Can not add or update a child row: a foreign key constraint fails

It is when it comes to making an insert / update in a table that contains a column that is a foreign key and that is not assigned a valid value, as in this case, a value that does not exist in column a the one that reference (municipio.id_municipio).

In this case it was about doing:

INSERT INTO persona 
(nombre,apellido,identidad,edad,sexo,hijos,telefono,id_municipio) 
VALUES ('juan','veliz','1517199600702','22','m','3','96453034','0');

If we look, we are trying to add 0 in the person.id_municipality column (foreign key), which is not possible since in the municipality table there was no municipality with an id_municipality equal to 0.

In this case it was solved obtaining a correct value for the column id_municipality to later be able to execute the statement sql correctly.

    
answered by 06.07.2018 в 20:48