Cannot Add or Update a Child Row: A Foreign Key Constraint Fails


I encountered this error when I tried to add a new child row using CakePhp. Checking around forums and coding sites, there is always one suggestion whenever somebody asks this question – make sure that the foreign key exists in the parent table. I made sure that the key exists in the parent table, but it still keep giving ke the same error.

I tried inserting the child row using phpMyAdmin.

I tried inserting the row using an SQL INSERT statement.

I tried editing a child row.

All of them spewed the same error.

After a few more hours of debugging, I had a lucky break. It turns out that I was using MyISAM as the table storage type rather than InnoDB. I changed the table and voila! I had no problem adding or editing child rows after that.

I’ve been using MySQL/MariaDB for years now, but I have barely scratched the surface.