0
votes

What I want to do is put a Foreign Key from users_table column id into users_order table in the column user_id but when I try to do it says this. what did I do wrong or is there any other way to add foreign key to table in PhpMyAdmin ?

#1452 - Cannot add or update a child row: a foreign key constraint fails (`users`.`#sql-4830_792`, CONSTRAINT `#sql-4830_792_ibfk_1` FOREIGN KEY (`id`) REFERENCES `user_order` (`user_id`))

Users

2
Can you write steps you are doing here? So I can understand what wrong you are doing. Have you made an index on 'user_id' column of 'user_order' table?Himanshu Upadhyay

2 Answers

2
votes

According to the docs,

For storage engines supporting foreign keys, MySQL rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.

The error you see indicates that you are trying to add a new row to a child table, for which mo matching row is present in your parent table. To fix it, you can either add the row in your parent table before inserting a row in your child table, or remove NOT NULL constraints (if any) and insert a NULL value in the corresponding column. Once you do it, you will be able to add the foreign key constraint.

0
votes

Your error said that the value that you are inserting into the foreign key does not exists in the parent table. so before insertion foreign value into child table make sure your value is in parent table