[英]How to pass a null value from HTML form to mysql db foreign key field
I have two tables: parent and child. 我有两个表:父母和孩子。 One of the child column references parent PRIMARY KEY with FOREIGN KEY constraint - child.parent_id references parent.parent_id. 子列之一引用具有FOREIGN KEY约束的父PRIMARY KEY-child.parent_id引用parent.parent_id。
Foreign key column in child tables allows NULLs values because when child will be created parent may be not known yet. 子表中的外键列允许使用NULL值,因为创建子项的时间可能未知。 But when info about parent will be assigned/updated i want to have referential integrity. 但是,当有关父项的信息将被分配/更新时,我希望具有参照完整性。
And now the question: 现在的问题是:
How to pass null value from HTML form to MySQL? 如何将空值从HTML表单传递给MySQL? Quotes '' or "" not working "foreign key constraint fails" probably because it passes empty string instead of null value. 用引号''或“”无效“外键约束失败”,可能是因为它传递了空字符串而不是空值。 Or maybe do I need to do some additional checking in PHP and convert it to null ? 或者,也许我需要在PHP中进行一些附加检查并将其转换为null?
CREATE TABLE IF NOT EXISTS `parent` (
`parent_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`surname` varchar(20) NOT NULL,
PRIMARY KEY (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `child` (
`child_id` int(11) NOT NULL AUTO_INCREMENT,
`child_name` varchar(20) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
PRIMARY KEY (`child_id`),
KEY `fk_parent_id` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
ALTER TABLE `child`
ADD CONSTRAINT `fk_parent_id` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`parent_id`);
您需要将空值转换为null或在PHP中编辑查询。
Why do you want to pass up a NULL
value when your tables do not support NULL
values in the parent? 为什么你想传递一个NULL
值时,你的表不支持NULL
父值? Also 也
`parent_id` int(11) DEFAULT NULL,
Should be NOT NULL
as a child should always have a parent. 应该NOT NULL
因为孩子应该始终有一个父母。
If you are trying to pass parent/child identifiers from a HTML form, I would recommend validating them server side in your PHP
code. 如果您尝试通过HTML表单传递父/子标识符,我建议在您的PHP
代码中在服务器端对其进行验证。 As I could easily manipulate the values in the markup and add any parent/child combination I wish. 因为我可以轻松地操纵标记中的值并添加我希望的任何父/子组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.