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

时间:2012-03-28 11:06:18

标签: php mysql phpmyadmin

我有两个表 - 用户和语言,其主键为“id”的外键链接。 我已经检查过表格的类型是innoDB。我有删除限制和更新-cascade。

此插入查询将其插入语言表:(它可以是多行,因为表单具有动态clickevent按钮而添加)

if(empty($_SESSION['user_id'])) { // user not logged in; redirect to somewhere else }

$sql_insert = "INSERT into `language`
 (`native`,`other`,`other_list`,`other_read`, `other_spokint`
 ,`other_spokprod`,`other_writ`  )
VALUES
 ('$native','$other','$other_list','$other_read','$other_spokint','$other_spokprod',
 '$other_writ') ";

mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());     
}

这是完整的错误:

Insertion Failed:Cannot add or update a child row: a foreign key constraint fails
(`members`.`language`, CONSTRAINT `language_ibfk_1` FOREIGN KEY (`id`) 
REFERENCES `users` (`id`))

任何帮助将不胜感激!

表格语言的表结构:

CREATE TABLE IF NOT EXISTS `language` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `native` varchar(30) NOT NULL,
 `other` varchar(30) NOT NULL,
 `other_list` varchar(9) NOT NULL,
 `other_read` varchar(9) NOT NULL,
 `other_spokint` varchar(9) NOT NULL,
 `other_spokprod` varchar(9) NOT NULL,
 `other_writ` varchar(9) NOT NULL,
  PRIMARY KEY (`id`)
  ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;


RELATIONS FOR TABLE `language`:
`id`
`users` -> `id`

1 个答案:

答案 0 :(得分:0)

你必须使用这样的结构:

create table users (
    id int not null auto_increment,
    <additional fields>,

    primary key (id)
) ENGINE=InnoDB;


create table language(
    id int not null auto_increment,
    user_id int not null,
    <additional fields>,

    primary key (id),
    foreign key (user_id) references users(id) on delete restrict on update cascade
) ENGINE=InnoDB;