Unable to Insert a Row in the Table with a Foreign Key Field

advertisements

I am working on a PHP application that uses a database extensively. My coworker who set up the database, set up the tables to use foreign keys. Here is the statement I am using:

INSERT INTO patients (ethnicity, gender)
VALUES (1, 1);

INSERT INTO sessions (patient_id, submitted, age_in_years, video, annotated)
VALUES (LAST_INSERT_ID(), NOW(), 0, '', FALSE);

The first statement works. However, I get the following error with the second statement.

#1452 - Cannot add or update a child row: a foreign key constraint fails (`<database name>/sessions`, CONSTRAINT `fk_sessions_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

I have confirmed that LAST_INSERT_ID() returns the expected value.

How can I fix this?

Below is how we set up the sessions table

CREATE TABLE IF NOT EXISTS `sessions` (
  `id` int(11) NOT NULL auto_increment,
  `patient_id` int(11) NOT NULL,
  `severity` enum('Minimal Symptoms of Autism Spectrum Disorder','Mild-to-Moderate Symptoms of Autism Spectrum Disorder','Severe Symtoms of Autism Spectrum Disorder') default NULL,
  `submitted` datetime default NULL,
  `age_in_years` int(11) NOT NULL,
  `video` text NOT NULL,
  `annotated` tinyint(1) default '0',
  PRIMARY KEY  (`id`),
  KEY `fk_sessions_1` (`patient_id`),
  KEY `age_in_years` (`age_in_years`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

ALTER TABLE `sessions`
  ADD CONSTRAINT `fk_sessions_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

EDIT: Removed unnecessary details. If you feel you need more, feel free to look at the first version of this post.


It turns out that when my coworker added the foreign key, he had a typo in the table name that the foreign key references.

ALTER TABLE `sessions`
  ADD CONSTRAINT `fk_sessions_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

should be

ALTER TABLE `sessions`
  ADD CONSTRAINT `fk_sessions_1` FOREIGN KEY (`patient_id`) REFERENCES `patients` (`id`) ON DELETE CASCADE;