简体   繁体   中英

Insert row into a table with foreign key inside PHP

I am creating a PHP website that use Apache web server (PHPmyAdmin)

I have 3 tables :

  1. brand
    • brand_id (PRIMARY KEY) AUTO INCREMENT
    • brand_name
  2. item
    • item_id (PRIMARY KEY) AUTO INCREMENT
    • item_category
  3. model
    • model_id (PRIMARY KEY) AUTO INCREMENT
    • item_model
    • brand_id (FOREIGN KEY for brand.brand_id)
    • brand_name (FOREIGN KEY for item.item_id)
    • quantity
    • price

I have a problem when I want to insert new value into model table.

this is PHP Code that I use for inserting

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')";

Note that I did not insert any value into the model_id because I think it will automatically increased for it is AUTO increment. I dont know whether I am right or wrong. the isset values are passed from another PHP file. so this PHP basically just catch the thrown values from previous PHP file.

I had tried to insert value directly from the PHPmyAdmin using SQL statement and it yielded this error :

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) 

and if I tried to put in a id value into one of the column, it will yield an error:

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' 

How do I insert a row into a table with foreign key inside PHP?

$sql = "INSERT INTO model (model_id,item_model, brand_id, item_id, quantity, price)
                VALUES (null,'$model', '$brand', '$cat', '$quantity', '$price')";

Try this.

Add auto increment field and pass value null

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