php - 违规 : 1452 Cannot add or update a child row: a foreign key constraint fails

标签 php mysql sql

First of all, it's not a duplicate! I already saw some related questions about it and I tried to do what they said in those answers and didn't work..

这是我的数据库结构的图像 entity relationship diagram

如您所见,一切正常,关系已正确建立但是当我尝试添加事件时出现此错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tvfootball.all_streams, CONSTRAINT fk_channels FOREIGN KEY (channel_id) REFERENCES channels (ID) ON DELETE CASCADE ON UPDATE NO ACTION)' in C:\xampp\htdocs\aaa\admin\addStream.php:16 Stack trace: #0 C:\xampp\htdocs\aaa\admin\addStream.php(16): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\aaa\admin\addStream.php on line 16

如果我尝试插入一个 channel ,我会得到这个错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tvfootball.all_streams, CONSTRAINT fk_events FOREIGN KEY (event_id) REFERENCES events (ID) ON DELETE CASCADE ON UPDATE NO ACTION)' in C:\xampp\htdocs\aaa\admin\addStream.php:31 Stack trace: #0 C:\xampp\htdocs\aaa\admin\addStream.php(31): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\aaa\admin\addStream.php on line 31

问题是...它向streams 表中插入数据,但不向all_streams 中插入任何内容

这是我的 SQL

DROP TABLE IF EXISTS `all_streams`;
CREATE TABLE `all_streams` (
  `event_id` int(11) DEFAULT '0',
  `stream_id` int(11) DEFAULT '0',
  `channel_id` int(11) DEFAULT '0',
  `date_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY `fk_streams` (`stream_id`),
  KEY `fk_events` (`event_id`),
  KEY `fk_channels` (`channel_id`),
  CONSTRAINT `fk_channels` FOREIGN KEY (`channel_id`) REFERENCES `channels` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `fk_events` FOREIGN KEY (`event_id`) REFERENCES `events` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `fk_streams` FOREIGN KEY (`stream_id`) REFERENCES `streams` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

这是我的 PHP

if(isset($_POST['addStreamsEvents'])){
extract($_POST);
$statement = $db->prepare("INSERT INTO streams (link) VALUES (?)");
$statement->bindParam(1,$stream);
$statement->execute();

$id=$db->lastInsertId();

$statement_join = $db->prepare("INSERT INTO all_streams (event_id,stream_id)VALUES (?,?)");
$statement_join->bindParam(1,$event);
$statement_join->bindParam(2,$id);
$statement_join->execute();
}

if(isset($_POST['addStreamsChannels'])){
    extract($_POST);
    $statement = $db->prepare("INSERT INTO streams (link) VALUES (?)");
    $statement->bindParam(1,$stream);
    $statement->execute();

    $id=$db->lastInsertId();

    $statement_join = $db->prepare("INSERT INTO all_streams (channel_id, stream_id) VALUES (?,?)");
    $statement_join->bindParam(1,$event);
    $statement_join->bindParam(2,$id);
    $statement_join->execute();
}

有人知道我做错了什么吗?

顺便说一句:

我已经试过了:SET FOREIGN_KEY_CHECKS=0; 但没用..

最佳答案

我注意到的第一件事是您在外键约束列上设置了默认值零,但是 you said in the comments ,零值不作为主键存在,因此您的插入失败,因为您没有在查询中指定它。

`event_id` int(11) DEFAULT '0',
`stream_id` int(11) DEFAULT '0',
`channel_id` int(11) DEFAULT '0',

如果您要继续使用此默认值,则必须显式插入 NULL 或有效 ID。

这是 a working example这改变了这个:

INSERT INTO all_streams (event_id,stream_id) VALUES (?,?)

进入这个:

INSERT INTO all_streams (event_id,stream_id,channel_id) VALUES (?,?, NULL)

但是,我认为最好的办法是删除这些默认值,因为这对我来说没有意义,which works also .

没有看到您的表单就不清楚,但您可能没有注意到的另一个问题是您正在为 event_id 使用名为 event 的相同输入值 channel 编号

$statement_join = $db->prepare("INSERT INTO all_streams (event_id,stream_id)VALUES (?,?)");
$statement_join->bindParam(1,$event);
...
$statement_join = $db->prepare("INSERT INTO all_streams (channel_id, stream_id) VALUES (?,?)");
$statement_join->bindParam(1,$event);

这是 the working example尽我所能为您的表格和表格填写缺失值。

<form method="POST">
    <input type="hidden" name="addStreamsEvents"/>
    <input type="hidden" name="addStreamsChannels"/>

    <label for="stream">Stream</label>
    <input type="text" name="stream"/>

    <label for="event">Event or Channel ID</label>
    <input type="number" name="event" value="1"/>

    <input type="submit" value="Submit"/>
</form>

<?php

// returns an instance of PDO
// https://github.com/jpuck/qdbp
$db = require __DIR__.'/streams_Dtm905_A.pdo.php';

if(isset($_POST['addStreamsEvents'])){
    extract($_POST);
    $statement = $db->prepare("INSERT INTO streams (link) VALUES (?)");
    $statement->bindParam(1,$stream);
    $statement->execute();

    $id=$db->lastInsertId();

    $statement_join = $db->prepare("INSERT INTO all_streams (event_id,stream_id) VALUES (?,?)");
    $statement_join->bindParam(1,$event);
    $statement_join->bindParam(2,$id);
    $statement_join->execute();
}

if(isset($_POST['addStreamsChannels'])){
    extract($_POST);
    $statement = $db->prepare("INSERT INTO streams (link) VALUES (?)");
    $statement->bindParam(1,$stream);
    $statement->execute();

    $id=$db->lastInsertId();

    $statement_join = $db->prepare("INSERT INTO all_streams (channel_id, stream_id) VALUES (?,?)");
    $statement_join->bindParam(1,$event);
    $statement_join->bindParam(2,$id);
    $statement_join->execute();
}
DROP TABLE IF EXISTS `all_streams`;
DROP TABLE IF EXISTS `streams`;
DROP TABLE IF EXISTS `events`;
DROP TABLE IF EXISTS `channels`;

CREATE TABLE `channels` (
  `id` int(11) AUTO_INCREMENT PRIMARY KEY,
  `name` varchar(11)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `events` (
  `id` int(11) AUTO_INCREMENT PRIMARY KEY,
  `something` varchar(11)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `streams` (
  `id` int(11) AUTO_INCREMENT PRIMARY KEY,
  `link` varchar(11)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `all_streams` (
  `event_id` int(11),
  `stream_id` int(11),
  `channel_id` int(11),
  `date_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY `fk_streams` (`stream_id`),
  KEY `fk_events` (`event_id`),
  KEY `fk_channels` (`channel_id`),
  CONSTRAINT `fk_channels` FOREIGN KEY (`channel_id`) REFERENCES `channels` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `fk_events` FOREIGN KEY (`event_id`) REFERENCES `events` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `fk_streams` FOREIGN KEY (`stream_id`) REFERENCES `streams` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- seed data
INSERT INTO `channels` (`name`)      VALUES ('channel 1');
INSERT INTO `events`   (`something`) VALUES ('event   1');

关于php - 违规 : 1452 Cannot add or update a child row: a foreign key constraint fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40428295/

相关文章:

javascript - 使用另一个帐户重新登录后 2 div 的奇怪行为

php - 如何在 PHP 中将 pi 计算为一组数字?

mysql - Laravel 可以迁移但仍然出现 PDOException

sql - SQL 命令中的 TIMESTAMP 和 CURRENT_TIMESTAMP 问题

php - 为用户报价创建唯一 ID

java - 如何使用 SQL 进行递归调用?

php - CakePHP:在调用parent::function()时使用父模型?

php - 如何使用codeigniter事件记录在mysql表的单个字段中搜索多个值?

php - 如何以数组形式将数据存储在数据库中

mysql - 无需登录到mysql用户即可备份mysql