【问题标题】:while / foreach loop updating quantity in mySQLmySQL中的while / foreach循环更新数量
【发布时间】:2015-02-16 17:12:24
【问题描述】:

我有一个脚本,我在其中获取购物车 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'] . "'");
                }
            }
            //

        }

但是,似乎什么都没有发生,我也没有收到错误消息。我在这里做错了什么?

【问题讨论】:

    标签: php mysql loops while-loop


    【解决方案1】:

    这对我来说看起来不对:

    // 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);
    

    【讨论】:

    • foreach 部分是不必要的/多余的,OP 可以直接从 while 循环内的 $cart_details 访问索引 quantity
    • 这完全是我的错...我只得到了 1 行的查询而不是数组! :(
    猜你喜欢
    • 2013-01-28
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 2020-05-15
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多