When I try to execute a SQL function within PHP this error occurs:
Can not add or update a child row: a foreign key constraint fails (
db_inventory
.vendedor
, CONSTRAINTidCiudadVendedor
FOREIGN KEY (id_ciudad_vendedor
) REFERENCESciudad
(id_ciudad
) ON DELETE NO ACTION ON UPDATE NO ACTION)
But, if I execute the structure MYSQL
from phpMyAdmin
no problem arises:
INSERT INTO 'vendedor' ('id_vendedor', 'nombre_vendedor', 'documento_vendedor', 'correo_vendedor', 'telefono_vendedor', 'codigo_vendedor', 'direccion_vendedor', 'id_ciudad_vendedor', 'id_empresa_vendedor') VALUES (NULL, 'Prueba', '222123', '[email protected]', '3408821', 'COD0134', 'Prueba', '888', '1');
Next I show the structure of the Seller table.
SALES STRUCTURE SQL
-- -----------------------------------------------------
-- Table 'db_inventory'.'vendedor'
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS 'db_inventory'.'vendedor' (
'id_vendedor' INT NOT NULL AUTO_INCREMENT,
'nombre_vendedor' VARCHAR(45) NOT NULL,
'documento_vendedor' VARCHAR(45) NOT NULL,
'correo_vendedor' VARCHAR(45) NOT NULL,
'telefono_vendedor' VARCHAR(20) NOT NULL,
'codigo_vendedor' VARCHAR(20) NOT NULL,
'direccion_vendedor' VARCHAR(45) NOT NULL,
'id_ciudad_vendedor' INT NOT NULL,
'id_empresa_vendedor' INT NOT NULL,
PRIMARY KEY ('id_vendedor'),
INDEX 'idCiudadVendedor_idx' ('id_ciudad_vendedor' ASC),
INDEX 'idEmpresaVendedor_idx' ('id_empresa_vendedor' ASC),
CONSTRAINT 'idCiudadVendedor'
FOREIGN KEY ('id_ciudad_vendedor')
REFERENCES 'db_inventory'.'ciudad' ('id_ciudad')
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT 'idEmpresaVendedor'
FOREIGN KEY ('id_empresa_vendedor')
REFERENCES 'db_inventory'.'empresa' ('id_empresa')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SQL CITY STRUCTURE
-- -----------------------------------------------------
-- Table 'db_inventory'.'ciudad'
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS 'db_inventory'.'ciudad' (
'id_ciudad' INT NOT NULL AUTO_INCREMENT,
'nombre_ciudad' VARCHAR(50) NOT NULL,
'id_departamento_ciudad' INT NOT NULL,
PRIMARY KEY ('id_ciudad'),
INDEX 'idCiudadDepartamento_idx' ('id_departamento_ciudad' ASC),
CONSTRAINT 'idCiudadDepartamento'
FOREIGN KEY ('id_departamento_ciudad')
REFERENCES 'db_inventory'.'departamento' ('id_departamento')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
PHP STRUCTURE
<?php
//Declaracion de cabeceras del sistema
header("Context-type: application/json;");
//Inclusion del archivo respectivo para la conexion con la BD
require '../Connection/connection.php';
session_start();
//Declaracion para decodificar los datos recibidos por POST
$_POST = json_decode(file_get_contents('php://input'), true);
//Declaracion del array para codificar en formato JSON la variable mensaje
$resultado = array();
//Evaluamos si la conexion a la BD se realiza correctamente
if ($mysqli)
{
if(isset($_POST) && !empty($_POST))
{
//Objeto convertido a formato UTF8 para insertar caracteres especiales en la BD del sistema
$mysqli->set_charset('utf8');
//Capturamos los valores de las variables
$nombreVendedor = $_POST['nombre_vendedor'];
$documentoVendedor = $_POST['documento_vendedor'];
$correoVendedor = $_POST['correo_vendedor'];
$direccionVendedor = $_POST['direccion_vendedor'];
$telefonoVendedor = $_POST['telefono_vendedor'];
$codigoVendedor = $_POST['codigo_vendedor'];
$ciudadVendedor = $_POST['ciudad_vendedor'];
$idEmpresa = $_SESSION['usuario']['id_empresa'];
/*
echo "Nombre: " . $nombreVendedor;
echo "Documento: " . $documentoVendedor;
echo "Correo: " . $correoVendedor;
echo "Direccion: " . $direccionVendedor;
echo "Telefono: " . $telefonoVendedor;
echo "Codigo: " . $codigoVendedor;
echo "Ciudad: " . $ciudadVendedor;
echo "ID: " . $idEmpresa;
*/
//Prepramos la consulta para INSERTAR datos en la Base de Datos a la tabla VENDEDOR
$consulta_sql = "INSERT INTO 'vendedor' ('id_vendedor', 'nombre_vendedor', 'documento_vendedor', 'correo_vendedor', 'telefono_vendedor', 'codigo_vendedor', 'direccion_vendedor', 'id_ciudad_vendedor', 'id_empresa_vendedor')
VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)";
$insertar_vendedor = $mysqli->prepare($consulta_sql);
echo "Echo consulta: " . "$consulta_sql";
//Usamos el metodo bind_param() para captar las variables en la Base de Datos
/*
*Las 'ssssssii' representan el tipo de dato
*/
$insertar_vendedor->bind_param('ssssssii', $nombreVendedor,
$documentoVendedor,
$correoVendedor,
$telefonoVendedor,
$codigoVendedor,
$direccionVendedor,
$ciudadVendedor,
$idEmpresa);
//Ejecutamos la consulta
if ($insertar_vendedor->execute())
{
/*
*Verificamos si hubo filas afectadas
*y decidimos el estado del mensaje con un operador ternario
*/
$insertedRows = $insertar_vendedor->affected_rows;
$mensaje = ($insertedRows > 0) ? "Se ha registrado correctamente el vendedor." : "No fue posible realizar el registro del vendedor, vuelve a intentarlo más tarde. " . $insertar_vendedor->error;
$resultado['mensaje'] = $mensaje;
}
else
{
$resultado['mensaje'] = "Ha ocurrido un error importante al tratar de ejecutar el SCRIPT: " . $mysqli->error;
// . $mysqli->error
}
}
else
{
$resultado['mensaje'] = "La petición con el respectivo método POST es inapropiado para la URL visitada.";
}
}
else
{
$resultado['mensaje'] = "No se ha podido establecer la conexion.";
}
echo json_encode($resultado);
?>
It should be noted that the Daughter table that in this case would be ciudad
contains values in their respective fields. So I discard this option:
This may occur because of what has already been said: there is between the two tables some data that would be orphaned by not existing in the other table.
Besides that it can be executed correctly from the MYSQL manager, so it seems very strange to me. so I'd like to know why this can happen?
Note: I know it can be considered as a duplicate but, of all the questions I saw about it, I did not find out why it can be Run correctly in the manager and not with the PHP Script.