Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert values into database with foreign key using php

Tags:

php

mysql

I am having trouble with the following issue: I have two tables:

category table:
category_id     |      category_name

brand table
brand_id     |      brand_name     |      category_id (FOREIGN KEY)

I was trying to insert a new brand name value using PHP with FOREIGN KEY that referenced to category id.

$insert = "INSERT INTO brand (category_id, brand_name) VALUES('$category_name','$brand')"; 

However it could not be added into the brand table.

like image 974
AWSFanatic Avatar asked Aug 23 '26 15:08

AWSFanatic


1 Answers

Foreign key means category_id in table brand is refer to the same category_id in table category, so the category_id inserted in table brand must exist in table category.

When you insert new record in table brand, you need to insert the ID (not the category name) and make sure that id is exist in table category

like image 164
Jeffry Evan Avatar answered Aug 25 '26 04:08

Jeffry Evan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!