简体   繁体   中英

Insert values into database with foreign key using php

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM