简体   繁体   中英

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 column in child tables allows NULLs values because when child will be created parent may be not known yet. 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? 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 ?

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? Also

`parent_id` int(11) DEFAULT NULL,

Should be NOT NULL as a child should always have a parent.

If you are trying to pass parent/child identifiers from a HTML form, I would recommend validating them server side in your PHP code. As I could easily manipulate the values in the markup and add any parent/child combination I wish.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM