Friday, 25 June 2010

Mysql foreign keys don't work

Recently I've been working on a small PHP+MySql project. I designed a database schema that contains multiple tables, some of them with FOREIGN KEY constraint defined. After my model was ready I exported it to SQL format and created the actual database from the script. I was very surprised discovering that the defined foreign keys constraints don't work i.e. I could add any data to the constrained columns regardless the content of referenced table.

Solution:
It came out that the problem was caused by the default ENGINE used by my MySql database i.e. MyISAM. Foreign key constraint is not implemented in its current version (read more here). To enable the FOREIGN KEY constraint I decided to use InnoDb ENGINE. I forced that by adding engine selection for each table:


CREATE TABLE IF NOT EXISTS `my_table` (
`id` INT NOT NULL ,
`other_table_id` INT NOT NULL ,
PRIMARY KEY (`id`) ,
FOREIGN KEY (`other_table_id` ) REFERENCES `other_table` (`id`)
) ENGINE = InnoDB;

No comments: