此脚本的目的是获取用户在表单中输入的产品的 ProductID,以及在先前脚本中创建的订单的 ID,然后将这两个值放入 order_line_item 表中。
我已经确定发生错误是因为名为“$db_productid”的变量中没有值,然后当我将此值插入数据库时,它会尝试查找具有该 ID 的产品,它可以链接到但没有产品ID 为 0,因此它返回以下错误:
无法添加或更新子行:外键约束失败(
the_shop
.order_line_item
, CONSTRAINTorder_line_item_ibfk_1
FOREIGN KEY (ProductID
) REFERENCESproduct
(ProductID
) ON DELETE CASCADE ON UPDATE CASCADE)
这是我的脚本:
if (isset($_GET['submit1'])) {
$dblastid = $_SESSION['lastid'];
$db_product_name = $_GET['product_name'];
$query = "SELECT ProductID FROM product WHERE Product_Name = '$db_product_name'";
$result = mysql_query($query)
or die(mysql_error());
$fetch = mysql_fetch_assoc($result);
$db_productid = $fetch['ProductID'];
$lastid = $_SESSION['lastid'];
$query = "INSERT INTO `the_shop`.`order_line_item`(
`OrderID` ,
`ProductID`
)
VALUES (
'$lastid', '$db_productid')";
$result = mysql_query($query)
or die(mysql_error());
}
经过进一步调试,我发现用户输入表单的字符串确实出现在“$db_product_name”中,并且具有此名称的产品位于产品表的数据库中