3

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.

3
  • 3
    Are you inserting category_name as value for category_id ? You should insert the category_id and make sure the id is present in the category table. Commented May 4, 2018 at 4:13
  • Thank you for your response, Yes i am trying to get the category_name fetched from my DB category table and insert it to the brand table. each brand name are pointing base to the selected category_name . Commented May 4, 2018 at 4:27
  • As has been pointed out, you have to insert the category_id into the brand table. When you want to retrieve data from the brand table, you can get the category name by using a query such as SELECT brand_name, category_name FROM brand b JOIN category c ON c.category_id=b.category_id Commented May 4, 2018 at 6:07

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, now I am able to insert new brand(value) to my database. but Is there any option to select the category_name instead of category_id. the scenario is I am trying to add new brand name reference to the category name inside the select tag that fetch from the category table,.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.