我正在创建一个使用 Apache 网络服务器 (PHPmyAdmin) 的 PHP 网站
我有 3 个表:
- 品牌
- brand_id(主键)自动递增
- 品牌名称
- 项目
- item_id(主键)自动递增
- 项目类别
- 模型
- model_id(主键)自动递增
- 项目模型
- brand_id(brand.brand_id 的外键)
- brand_name(item.item_id 的外键)
- 数量
- 价格
当我想向模型表中插入新值时遇到问题。
这是我用来插入的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')";
试试这个。
添加自增字段并传值为null
关于php - 在 PHP 中使用外键将行插入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25782151/