while / foreach循环更新mySQL中的数量

时间:2014-12-18 01:18:35

标签: php mysql loops while-loop

我有一个脚本,我将获取购物车ID,然后根据产品是否已付款降低可用性计数。每个购物车可能包含1或10个产品,因此每件商品都会发生这种情况。当有人支付(通过PayPal IPN确认)时,我正在运行:

// we set the cart id, 12345 in this case
$cart_id = '12345'

// we get the buyer ID
$buyer_id = $db->get_sql_field("SELECT buyer_id FROM db_carts WHERE sc_id='" . $cart_id . "'", "buyer_id");

// we get the products.
$sql_select_cart = $db->query("SELECT item_id, quantity FROM db_shopping_carts_items WHERE sc_id='" . $cart_id . "'");

while ($cart_details = $db->fetch_array($sql_select_cart))
        {

            //
            foreach ($cart_details as $key => $item_details)
            {
                if ($item_details['quantity']<='100')
                {
                    $db->query("UPDATE db_products SET quantity=quantity-" . $item_details['quantity'] . 
                    " WHERE product_id='" . $item_details['item_id'] . "'");
                }
            }
            //

        }

然而,似乎没有任何事情发生,我也没有收到错误消息。我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

这对我来说不对:

// we get the products.
$sql_select_cart = $db->query("SELECT item_id, quantity FROM db_shopping_carts_items WHERE sc_id='" . $cart_id . "'");

while ($cart_details = $db->fetch_array($sql_select_cart))

假设有mysqli,你需要这样的东西:

// we get the products.
$sql_select_cart = $db->query("SELECT item_id, quantity FROM db_shopping_carts_items WHERE sc_id='" . $cart_id . "'");

while ($cart_details = $sql_select_cart->fetch_array())

请注意,您似乎在错误的对象上使用fetch_array()并且您传递的是无效参数。

要确保您看到任何错误,您需要确保显示它们,并且应该检查它们,例如告诉mysqli抛出异常。要做到这一点,请在脚本的顶部:

ini_set('display_errors',1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);