我的 php 算法有问题。它应该将客户订购的商品插入数据库。当订单总额小于12磅需要送货时,需要在多维数组$orderItems中添加送货费用。当订单总额大于或等于 20 磅时,将向此数组添加免费商品。对浏览器的响应显示数组已正确添加,但 SQL 查询似乎不包含我在 PHP 中添加到数组的项目。数组中已有的任何其他项目都可以毫无问题地添加并在数据库中正常显示。
我需要帮助让我的算法添加 $orderItems 多维数组中的所有项目。
PHP:
if (($orderTotal < 12.00) && ($deliveryorcollection == "Delivery") == TRUE)
{
array_push($orderItems, array('dish_id' => "1F", 'dish_name' => "Delivery Charge 1", 'dish_size' => "Regular", 'dish_quantity' => 1, 'dish_price' => 1.00));
}
if ($orderTotal >= 20.00)
{
array_push($orderItems, array('dish_id' => "1E", 'dish_name' => "Mini Vegetarian Spring Rolls", 'dish_size' => "Regular", 'dish_quantity' => 1, 'dish_price' => 0.00));
}
var_dump($orderItems);
foreach ($orderItems as $k => $cur)
{
$sql = "INSERT INTO `airsofto_YummyYummy`.`ItemOrders` (`OrderID`, `DishID`, `OrderQuantity`, `DishSize`) VALUES ('$orderid', '$cur->dish_id', '$cur->dish_quantity', '$cur->dish_size')";
//Line where the error occurs^
if ($conn->query($sql) === TRUE)
{
echo "New itemOrder record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn -> error;
}
}
这是它打印到浏览器的内容:
array(2) { [0]=> object(stdClass)#1 (5) { ["dish_id"]=> int(55) ["dish_name"]=> string(17) "Chicken Chow Mein" ["dish_size"]=> string(5) "Large" ["dish_quantity"]=> string(1) "1" ["dish_price"]=> float(4.6) } [1]=> array(5) { ["dish_id"]=> string(2) "1F" ["dish_name"]=> string(17) "Delivery Charge 1" ["dish_size"]=> string(7) "Regular" ["dish_quantity"]=> int(1) ["dish_price"]=> float(1) } } New itemOrder record created successfullyError: INSERT INTO
airsofto_YummyYummy
.ItemOrders
(OrderID
,DishID
,OrderQuantity
,DishSize
) VALUES ('161', '', '', '') Cannot add or update a child row: a foreign key constraint fails (airsofto_YummyYummy
.ItemOrders
, CONSTRAINTItemOrders_ibfk_2
FOREIGN KEY (DishID
) REFERENCESDishes
(DishID
))
您可以看到数组已成功添加,但 SQL 查询不包含包含添加的送货费用的数组元素中的菜肴 ID、菜肴名称、菜肴大小、菜肴数量或菜肴价格。
我会注意到数据库中的 DishID 列是 varchar。
提前非常感谢。如果有任何其他可能有帮助的信息,请发表评论。
最佳答案
JonStirling 评论了答案。谢谢!
我需要将数组转换为对象...
array_push($orderItems, (object) array('dish_id' => "1F", 'dish_name' => "Delivery Charge 1", 'dish_size' => "Regular", 'dish_quantity' => 1, 'dish_price' => 1.00));
关于php - MySQL 查询不插入在 PHP 中添加的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34046506/