0

我有 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 无法添加或更新子行:外键约束失败(test. times, CONSTRAINT times_ibfk_2FOREIGN KEY ( id) REFERENCES students ( id) ON DELETE CASCADE ON UPDATE CASCADE)

除此之外,第一个查询(students.php 和第二个查询 studentinfo.php)插入得很好。相同的 ID,插入到表中的登录时间出现问题:次。

在 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());
        }   
?>
4

2 回答 2

0

你的桌子设计在我看来是错误的。我假设times表中的每一行都可以有多个条目students。在这种情况下,您将需要以下列times

id - PK
student_id - FK
signintime
counselor_start_time
additional_time
finish_time

然后,特定学生的每一行将具有相同的student_id值,但id值不同。

于 2013-01-15T15:13:11.703 回答
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也称为父表)。允许在StudentIDtable 的列上插入的唯一值AddressList只是1 and 2因为这些是ID在 table 上找到的唯一值StudentList

当您尝试插入 ID 不是1 and 2表上的记录时Address,例如

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

它会产生一个错误,告诉你:

无法添加或更新子行:外键约束失败(db_2_ec2e8. addresslist, CONSTRAINT tb_fkFOREIGN KEY ( StudentID) REFERENCES studentlist( ID)):

因为在表中插入的列的值StudentID在父表 ( StudentList ) 上不可用。

所以,我希望这能帮助你现在理解。

于 2013-01-15T15:24:05.817 回答