I'm trying to get the column id data from one table (user_info) and insert it in to another (user_profile). I'm really not sure what the error means, but you can see it in its entirety below along with the schema information for each table respectively.
There are lots of posts related to this question on SO, however i can't find anything that relates closely the my particular issue and haven't been able to apply a fix as suggested in the numerous threads.
Error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
user_info
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
user_profile
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
The query, see third try block (included all that are related in case it helps
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 has a foreign key 'f_key' which should contain an 'id' from user_info table. It's empty in your insert statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.