PHP:无法添加或更新子行:外键约束失败

时间:2018-06-22 17:24:45

标签: php database mysqli

所以我有3张桌子,如下:

company

enter image description here

address

enter image description here

company_address

enter image description here


我试图通过使用company_id$_GETaddress_id获取mysqli_insert_id来向特定公司添加地址信息。但是当我提交时,它只会给我错误

  

无法添加或更新子行:外键约束失败(chkdcrmcompany_address,CONSTRAINT company_address_company_id外键(company_id)参考companycompany_id)删除级联上

问题出在哪里?我不知道...


php代码:

<?php
  require_once '../conn.php';
  $company_id = isset($_GET['company_id'])? $_GET['company_id'] : '';
  //Defining variables and parameters...
  $sql1 = "INSERT INTO address ... VALUES ...";
  //Binding parameters...
  $address_id = mysqli_insert_id($conn);
  mysqli_stmt_close($stmt1);

  $sql2 = "INSERT INTO company_address (company_id, address_id) VALUES 
  ($company_id, $address_id)";
  mysqli_query($conn, $sql2) or die(mysqli_error($conn));

  mysqli_close($conn);}
?>

表定义:

CREATE TABLE IF NOT EXISTS `chkdcrm`.`company_address` (
  `address_id` INT(11) NOT NULL,
  `company_id` INT(11) NOT NULL,
  PRIMARY KEY (`address_id`, `company_id`),
  CONSTRAINT `company_address_address_id`
    FOREIGN KEY (`address_id`)
    REFERENCES `chkdcrm`.`address` (`address_id`)
    ON DELETE CASCADE,
  CONSTRAINT `company_address_company_id`
    FOREIGN KEY (`company_id`)
    REFERENCES `chkdcrm`.`company` (`company_id`)
    ON DELETE CASCADE)
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `chkdcrm`.`address` (
  `address_id` INT(11) NOT NULL AUTO_INCREMENT,
  `type` ENUM('Invoice', 'Shipping', 'Site', 'Mailing') NOT NULL,
  `street` VARCHAR(100) NOT NULL,
  `city` VARCHAR(100) NOT NULL,
  `state` VARCHAR(30) NOT NULL,
  `zip` VARCHAR(10) NOT NULL,
  `country` VARCHAR(40) NOT NULL,
  PRIMARY KEY (`address_id`))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `chkdcrm`.`company` (
  `company_id` INT(11) NOT NULL AUTO_INCREMENT,
  `name_de` VARCHAR(150) NOT NULL  ,
  `website` VARCHAR(255) NULL  ,
  `parent_company` INT(11) NULL,
PRIMARY KEY (`company_id`),
  CONSTRAINT `parent_company`
    FOREIGN KEY (`parent_company`)
    REFERENCES `chkdcrm`.`company` (`company_id`)
    ON DELETE SET NULL)
ENGINE = InnoDB;

2 个答案:

答案 0 :(得分:0)

我已经经历了很多事情..我唯一能告诉你的是,您必须删除其他表中的所有引用,才能删除具有约束的内容。

我感觉到您正在尝试将table1中不存在的ID值插入到table2中。 (如果很忙,我建议在对表执行任何操作之前先禁用外键检查。

您只需

  SET FOREIGN_KEY_CHECKS=0

这将禁用与任何其他表的外键匹配。处理完表格后,再次启用它

SET FOREIGN_KEY_CHECKS=1

答案 1 :(得分:0)

您需要检查提交的公司ID是否在其父表(公司)中存在。如果可以,那么应该可以。

$checkcomp = "SELECT 1 FROM company WHERE company_id = $company_id";
$checking = $conn->query($checkcomp);
if($checking->num_rows > 0){
  //execute your insert
}
else{some error handling
}

旁注,我宁愿使用POST而不是GET