1

Here is my erd diagram of my tables...

I am trying to INSERT VALUES into my items table using the following code...

INSERT INTO items (item, addedby, updated_at, created_at) VALUES ("one","two" NOW(), NOW())

I am getting the following error...

11:15:53    INSERT INTO items (item, addedby, updated_at, created_at) VALUES ("one", "two", NOW(), NOW())   Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`wishlist`.`items`, CONSTRAINT `fk_items_users` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) 0.046 sec

Whats going on!?

Erik Åsland
  • 9,542
  • 10
  • 30
  • 58
  • Possible duplicate of [MySQL Error Code 1452 Foreign Key Constraint](http://stackoverflow.com/questions/22210461/mysql-error-code-1452-foreign-key-constraint) – castis Nov 16 '15 at 19:18
  • addedby user=2 fails, if there is no corresponding user 2 in the `users` table. However, your original `INSERT` statement has integers `1,2` while the printed error message spells them out as `"one","two"`. Do you have some sort of text filter in your application code which is modifying those values? – Michael Berkowski Nov 16 '15 at 19:21

1 Answers1

1

When you add relations in MySQL Workbench, it creates foreign key constraints automatically. Which means you have to provide a value for users_id which corresponds to an id in your users table.

If we assume you want to add an item for the user with id 1, your statement should look like this:

INSERT INTO items (item, addedby, updated_at, created_at, users_id) VALUES ("one","two" NOW(), NOW(), 1)

For further information look up referential integrity.

If you have just added the user and don't know his id because it's an AUTO_INCREMENT value, you can use LAST_INSERT_ID() to retrieve it.

abi
  • 81
  • 6