php - 在 PHP 中使用外键将行插入表中

标签 php mysql sql

我正在创建一个使用 Apache 网络服务器 (PHPmyAdmin) 的 PHP 网站

我有 3 个表:

  1. 品牌
    • brand_id(主键)自动递增
    • 品牌名称
  2. 项目
    • item_id(主键)自动递增
    • 项目类别
  3. 模型
    • 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/

相关文章:

c# - 如何防止秘书使用sql查询插入与另一个相同专业的医生相似的医生可用性?

php - 根据数组值使用Where子句查询数据库

sql - 创建表,其中每一列都是从选择查询中检索到的不同值

php - MySQL 查询仅加载某些项目

php - 类型 : Error Message: Call to a member function result() on string Filename: CI\application\models\Country_model. php 行号:34

PHP 时区列表

MySQL CLI 客户端将数据显示为十六进制

php - 该查询不适用于该表,那么如何使用该表更新查询该公式?

java - 基于用户和组的文件夹权限

mysql - 相当于在MySQL中处理字符串的explode()