MySQL查询没有插入在PHP

时间:2015-12-02 15:28:09

标签: php mysql multidimensional-array

我的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] =&gt; object(stdClass)#1(5){[&#34; dish_id&#34;] =&gt; int(55)[&#34; dish_name&#34;] =&gt; string(17)&#34; Chicken Chow Mein&#34; [&#34; dish_size&#34;] =&GT; string(5)&#34; Large&#34; [&#34; dish_quantity&#34;] =&GT;字符串(1)&#34; 1&#34; [&#34; dish_price&#34;] =&GT; float(4.6)} [1] =&gt; array(5){[&#34; dish_id&#34;] =&gt;字符串(2)&#34; 1F&#34; [&#34; dish_name&#34;] =&GT;字符串(17)&#34;交付费用1&#34; [&#34; dish_size&#34;] =&GT; string(7)&#34; Regular&#34; [&#34; dish_quantity&#34;] =&GT; int(1)[&#34; dish_price&#34;] =&gt; float(1)}}成功创建新的itemOrder记录错误:INSERT INTO airsofto_YummyYummyItemOrdersOrderIDDishIDOrderQuantityDishSize)价值观(&#39; 161&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;)   无法添加或更新子行:外键约束失败(airsofto_YummyYummyItemOrders,CONSTRAINT ItemOrders_ibfk_2 FOREIGN KEY(DishID)REFERENCES Dishes({{ 1}}))

您可以看到数组已成功添加,但SQL查询不包含包含添加的运费的数组元素中的dish_id,dish_name,dish_size,dish_quantity或dish_price。

我会注意到数据库中的DishID列是varchar。

非常感谢提前。如果还有其他任何可能有用的信息,请发表评论。

1 个答案:

答案 0 :(得分:0)

JonStirling回答了这个问题。谢谢!

我需要将我的数组作为对象投射......

array_push($orderItems, (object) array('dish_id' => "1F", 'dish_name' => "Delivery Charge 1", 'dish_size' => "Regular", 'dish_quantity' => 1, 'dish_price' => 1.00));