我的网站上有一个注册表单,它将向客户发出一个 user_id(父表),然后是成员表中的member_id。成员表引用父表,但似乎不会存储外键。我不确定如何解决这个问题,而且我对 sql 很陌生。
无法添加或更新子行:外键约束失败(gadgets
.member
, CONSTRAINT member_ibfk_1
FOREIGN KEY ( user_id
) 引用 user
(user_id
) ON DELETE CASCADE ON UPDATE CASCADE)
Query: INSERT INTO member (first_name, last_name, address, city, post_code, phone, email, date) VALUES ('bob', 'all','33 wildown','london','n4','020','bob', NOW())
CREATE TABLE IF NOT EXISTS `member` (
`member_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(32) NOT NULL,
`last_name` varchar(32) NOT NULL,
`address` varchar(60) NOT NULL,
`city` varchar(32) NOT NULL,
`post_code` varchar(32) NOT NULL,
`phone` int(15) NOT NULL,
`email` varchar(45) NOT NULL,
`date` date NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`member_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ;
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`password` varchar(30) NOT NULL,
`type` enum('member','admin') NOT NULL DEFAULT 'member',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;
-- Constraints for table `member`
--
ALTER TABLE `member`
ADD CONSTRAINT `member_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
这是我的 php
if (empty($errors)) {//如果一切正常。
// Register the user in the database...
// Make the query:
$q2 = "INSERT INTO user ( username, password) VALUES ('$un', SHA1('$p') )";
$q = "INSERT INTO member (first_name, last_name, address, city, post_code, phone, email, date) VALUES ('$fn', '$ln','$a','$c','$pc','$pn','$e', NOW())";
$r = @mysqli_query ($dbc, $q2);
$r = @mysqli_query ($dbc, $q);
// Run the query.
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Thank you!</h1>
<p>You are now registered.</p><p><br /></p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbc); // Close the database connection.
// Include the footer and quit the script:
include ('includes/footer.html');
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
最佳答案
如果您要将其用作外键,则需要从第一个插入中检索 user_id 并将其包含在第二个插入中。您尝试在成员表中创建一条记录而不指定 user_id,但您的 CREATE 语句将其设置为 NOT NULL。
关于php - 注册帐户时无法添加或更新子行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22491075/