我正在创建一个使用Apache Web服务器(PHPmyAdmin)的PHP网站
我有3张桌子:
牌
brand_id(主键)自动增加
品牌
项目
item_id(主键)自动增加
item_category
模型
model_id(PRIMARY KEY)自动增加
item_model
brand_id(brand.brand_id的FOREIGN KEY)
brand_name(item.item_id的FOREIGN KEY)
数量
价钱
我想在模型表中插入新值时遇到问题。
这是我用来插入的PHP代码
if (isset($_POST['brand_id']));
$brand = ($_POST['brand_id']);
if (isset($_POST['item_id']));
$cat = ($_POST['item_id']);
if (isset($_POST['model']));
$model = ($_POST['model']);
if (isset($_POST['quantity']))
$quantity = ($_POST['quantity']);
if (isset($_POST['price']))
$price = ($_POST['price']);
$sql = "INSERT INTO model (item_model, brand_id, item_id, quantity, price)
VALUES ('$model', '$brand', '$cat', '$quantity', '$price')";
请注意,我没有在model_id中插入任何值,因为我认为它会自动增加,因为它是AUTO增量。我不知道我是对还是错。
isset值是从另一个PHP文件传递的。因此,该PHP基本上只是捕获先前PHP文件中引发的值。
我曾尝试使用SQL语句直接从PHPmyAdmin插入值,但产生此错误:
Cannot add or update a child row: a foreign key
constraint fails (`stock`.`model`, CONSTRAINT `fk_item_brand`
FOREIGN KEY (`brand_id`) REFERENCES `brand` (`brand_id`) ON UPDATE CASCADE)
如果我尝试将id值放入其中一列,则会产生错误:
SQL query:
INSERT INTO `model`(`model_id`, `item_model`, `brand_id`, `item_id`, `quantity`, `price`)
VALUES (1,'a','1','1','a','a')
MySQL said: Documentation
#1062 - Duplicate entry '1' for key 'PRIMARY'
如何在PHP中使用外键将表插入行?
最佳答案
$sql = "INSERT INTO model (model_id,item_model, brand_id, item_id, quantity, price)
VALUES (null,'$model', '$brand', '$cat', '$quantity', '$price')";
尝试这个。
添加自动增量字段并传递空值
关于php - 在PHP中使用外键将行插入表中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25782151/