(SQL)包含null外键错误的更新行

时间:2017-10-06 16:07:34

标签: php mysql

我正在开发一个数据库项目。当我尝试更新包含null外键的行时,它会给我Cannot add or update a child row: a foreign key constraint fails ("archaelogy"."artifact", CONSTRAINT "location" FOREIGN KEY ("location_id") REFERENCES "location" ("location_id") ON DELETE NO ACTION ON UPDATE SET NULL错误。我可以添加一行包含null外键但不能更新它。

这是我的PHP代码:

function editArtifact($editData){
$query = "UPDATE artifact SET worker_id=?, image=?, period=?,location_id=?, coordinate_x=?, coordinate_y=?, type=?, comment=?) WHERE artifact_id=?";
$stmt = $this->con->prepare($query);
$stmt->bind_param("ibsiddsss", $editData['worker_id'],$editData['image'],$editData['period'],$editData['location_id'],$editData['coordinate_x'],$editData['coordinate_y'],$editData['type'],$editData['comment'],$editData['artifact_id']);

if ($stmt->execute()) {
  echo json_encode(array("editStatus"=>array('success'=>true)));
}else{
  echo json_encode(array("editStatus"=>array('success'=>false)));
}

$stmt->close();

}

这是我的帖子:

artifact_id=qw & worker_id=1 & image=null & period=null & location_id=null & coordinate_x=null & coordinate_y=null & type=null & comment=null

数据库设计:

database design

我不明白,我可以插入一个空列,但无法更新它。

2 个答案:

答案 0 :(得分:2)

我认为您正在尝试更新artifact location_id表中不存在的location值。另请检查您的帖子参数location_id=null。您的location_id表格中可能没有location为空。希望这可以帮助!

location_id表中的artifact应允许NULL值。

注意:要使用SET NULL规则进行更新/删除操作,外键列应允许NULL值,否则SET NULL规范将因生成错误消息而失败。

答案 1 :(得分:1)

好的,我解决了这个问题。问题出在我的PHP代码上。我试图用isset结构确定空值。当我尝试使用' ==='确定null时,问题已修复。

修正了php代码:

Comparable

感谢大家试图解决问题。我从Android应用程序发布数据。我不知道为什么发布空字符串。