MySql约束违规。插入

时间:2013-01-15 15:10:08

标签: php mysql sql foreign-keys

我有5个表的数据库

students    PK    : ID -> anum, first, last
studentinfo PK/FK : ID -> why, student_commenets, finished, aidyear
Times       PK/FK : ID -> signintime, counselor_start_time, 
                           additional_time, finish_time
counselor   PK/FK : ID -> firstcounselor, secondcounselor, thirdcounselor
Comments    PK/FK : ID -> counselorcomments, additional_commenets

我有一个名为signinpage.php的页面

在那个页面上我必须写三个不同的表(学生,学生信息和时间)

我的代码就是休闲:

if (empty($errors) === true) 
{
include('core/queries/inserts.updates.selects/students.php');   
include('core/queries/inserts.updates.selects/studentinfo.php');
include('core/queries/inserts.updates.selects/signintime.php'); 

$dbh = null;    
header('location: signedin.php');
exit(); 
}

每个文件都是实际的插入查询。 (如果你们需要看到它们,我会更新这篇文章)

我遇到的错误是:

  

SQLSTATE [23000]:完整性约束违规:1452无法添加或   更新子行:外键约束失败(testtimes,   约束times_ibfk_2外键(id)参考students   (id)ON UPETE CASCADE ON UPDATE CASCADE)

再加上这个,第一个查询(students.php和第二个查询studentinfo.php) 插入就好了。相同的ID,登录到表格中的signintime会出现问题:次。

在phpmyadmin中,两个表(studentinfo和times)都配置相同,两者都有删除级联并更新到原始表(学生),因为学生他/她启动会话(这是PK ID)。

我该如何解决这个错误?

编辑:

<?php
require('core/init.php');

try 
{
    $null = NULL;
    $query = $dbh->prepare("INSERT INTO `times` (signintime) VALUES (:signintime)");
    $query->bindParam(':signintime' , $null);
    $query->execute();
}

        catch (PDOException $e) 
        {
                error_log($e->getMessage());
                die($e->getMessage());
        }   
?>

2 个答案:

答案 0 :(得分:0)

你的桌面设计对我来说不对劲。我假设times表中的students表中的每一行都有多个条目。在这种情况下,您需要times中的以下列:

id - PK
student_id - FK
signintime
counselor_start_time
additional_time
finish_time

然后,特定学生的每一行都会有相同的student_id值,但值不同id

答案 1 :(得分:0)

以下陈述和示例与您提到的表格不同,但思想仍然相同

生成错误的原因是您尝试在表上插入一个值,其中 parent 表中尚未显示该值。 表意味着它依赖于另一个表(是父)。

要进一步解释,请考虑以下架构

CREATE TABLE StudentList
(
  ID INT PRIMARY KEY,
  NAme VARCHAR(50)
);

CREATE TABLE AddressList
(
  StudentID INT,
  Address VARCHAR(50),
  CONSTRAINT tb_fk FOREIGN KEY (StudentID) 
    REFERENCES StudentList(ID)
);

INSERT INTO StudentList VALUES (1, 'Jon');
INSERT INTO StudentList VALUES (2, 'Skeet');

INSERT INTO AddressList VALUES (1, 'Hello');
INSERT INTO AddressList VALUES (2, 'World');
INSERT INTO AddressList VALUES (1, 'Other Address');

有两个表:StudentListAddressList。表Address是子表,它依赖于表StudentList也称为父表)。允许在表StudentID的列AddressList上插入的唯一值仅为1 and 2,因为这些值是表ID上找到的唯一StudentList

当您尝试在表1 and 2上插入ID为Address以外的记录时,例如

INSERT INTO AddressList VALUES (1, 'Other Address');

它会产生错误,告诉:

  

无法添加或更新子行:外键约束失败   (db_2_ec2e8addresslist,CONSTRAINT tb_fk FOREIGN KEY   (StudentID)参考studentlistID)):

因为父表上没有插入表StudentID列的值( StudentList )。

所以,我希望这会帮助你理解。

相关问题