0

I have two tables that am trying to link, a User table and Registration table:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL auto_increment,
  `first_name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

CREATE TABLE IF NOT EXISTS `registration` (
  `userid` int(11) NOT NULL,
  `sex` varchar(10) NOT NULL,
  `dob` date NOT NULL,
  `location` varchar(30) NOT NULL,
  `edu_level` varchar(32) NOT NULL,
  `work` varchar(30) NOT NULL,
  `rel_status` varchar(10) NOT NULL,
  KEY `userid` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

And I created a link between them with the design tab in phpadmin, but when am inserting records into the registration table, it keeps saying this:

Cannot add or update a child row: a foreign key constraint fails

(`letzfuze/registration`, CONSTRAINT `registration_ibfk_1` 
FOREIGN KEY (`userid`) REFERENCES `users` (`id`))

Please who can help?

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43

1 Answers1

1

The value supplied for the userid column in the registration table MUST ALREADY APPEAR in the id column of a row in users.

The foreign key constraint is essentially saying: "Do not allow a row to be added to the registration table if the value of the userid column is not found as a value of the id column in the users table."

The error message you are getting looks like the behavior we expect when an attempt is made to violate the constraint.

Here's a suggestion:

Insert the new row to users first, get the id value from that row, and then use that value for the userid column in registration.

If you can't do that, you might want to consider using a NULL value for the userid column, or ditching the foreign key constraint and altogether re-thinking your design.

spencer7593
  • 106,611
  • 15
  • 112
  • 140
  • Thats the process actually to first register the user using their Name, email and password, and after that, it takes you to the main registration form where you further register by typing in your sex, dob etc.. but after I hit the submit key, it gives me the error – Joshua Lawson May 12 '15 at 19:01