I am creating a PHP website that use Apache web server (PHPmyAdmin)
I have 3 tables :
- brand
- brand_id (PRIMARY KEY) AUTO INCREMENT
- brand_name
- item
- item_id (PRIMARY KEY) AUTO INCREMENT
- item_category
- 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?