我正在创建一个使用Apache Web服务器(PHPmyAdmin)的PHP网站
我有3张桌子:
当我想在模型表中插入新值时,我遇到了问题。
这是我用于插入的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中使用外键向表中插入行?
答案 0 :(得分:0)
$sql = "INSERT INTO model (model_id,item_model, brand_id, item_id, quantity, price)
VALUES (null,'$model', '$brand', '$cat', '$quantity', '$price')";
试试这个。
添加自动增量字段并传递值为空