使用php使用外键将值插入数据库

时间:2022-09-26 08:21:54

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.

我试着用带有外键的PHP插入一个新的品牌名值,该键引用类id。

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

However it could not be added into the brand table.

但是不能添加到品牌表中。

1 个解决方案

#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.

外键意味着表品牌中的category_id指的是表类别中的相同的category_id,所以在表品牌中插入的category_id必须存在于表类别中。

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

在表品牌中插入新记录时,需要插入ID(而不是类别名称),并确保在表类别中存在ID

#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.

外键意味着表品牌中的category_id指的是表类别中的相同的category_id,所以在表品牌中插入的category_id必须存在于表类别中。

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

在表品牌中插入新记录时,需要插入ID(而不是类别名称),并确保在表类别中存在ID