我的PHP算法出现问题。它应该将客户订购的物品插入到数据库中。当订单总额小于12磅并且要交货时,交货费用将被添加到多维数组$ orderItems中。当订单总额大于或等于20磅时,免费项目将被添加到此阵列中。对浏览器的响应显示数组正在被正确添加,但SQL查询似乎没有包含我在PHP中添加到数组的项目。已经在数组中的任何其他项目都可以毫无问题地添加并在数据库中正常显示。MySQL查询不插入在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查询没有按不包含来自包含添加的传送费用的数组元素的dish_id,dish_name,dish_size,dish_quantity或dish_price。
我会注意到数据库中的DishID列是一个varchar。
非常感谢提前。如果还有其他任何可能有用的信息,请发表评论。
看起来像你期待'$ orderItems'是对象的数组,但你的'array_push'呼叫加入阵列。这可能没有帮助。 –
不要你有一个SQL错误? – mlwacosmos
@JonStirling我正在研究你的建议。谢谢。 – Oli