![](/img/trans.png)
[英]SQLSTATE[23000]: Integrity constraint violation: 1048 Laravel 4
[英]SQLSTATE[23000]: Integrity constraint violation
我正在尝试从一个表(user_info)中获取列ID数据并将其插入到另一个表(user_profile)中。 我真的不确定该错误意味着什么,但是您可以在下面分别完整地看到它以及每个表的架构信息。
有很多与此问题相关的帖子,但是我找不到与我的特定问题密切相关的任何内容,并且无法按照众多主题中的建议进行修复。
错误
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
用户信息
CREATE TABLE `user_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(12) COLLATE utf8_unicode_ci NOT NULL,
`pass` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`joined` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=62 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
用户资料
CREATE TABLE `user_profile` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`f_key` int(11) NOT NULL,
PRIMARY KEY (`user_id`),
KEY `f_key` (`f_key`),
CONSTRAINT `user_profile_ibfk_1` FOREIGN KEY (`f_key`) REFERENCES `user_info` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
查询,请参阅第三个try块(包括所有相关的块,以防它有助于
try {
$result = $db->prepare("SELECT id FROM user_info WHERE username = :user");
$result->bindParam(':user', $username);
$result->execute();
$user_info = $result->fetch();
$id = $user_info[0];
}
catch (Exception $e) {
echo $e->getMessage();
}
try {
$result = $db->prepare("SELECT EXISTS( SELECT username FROM user_info WHERE username = :user)");
$result->bindParam(':user', $get_username);
$result->execute();
$user_exists = $result->fetch();
$exists = $user_exists[0];
}
catch (Exception $e) {
echo $e->getMessage();
}
if (isset($_POST['submitProfile'])) {
try {
$result = $db->prepare("INSERT INTO user_profile (user_id) VALUES (:id)");
$result->bindParam(':id', $id);
$result->execute();
}
catch (Exception $e) {
echo $e->getMessage();
}
}
user_profile具有一个外键“ f_key”,该外键应包含user_info表中的“ id”。 您的插入语句中为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.