【问题标题】:shopping cart - only update 1 entry购物车 - 仅更新 1 个条目
【发布时间】:2026-02-24 04:10:01
【问题描述】:

下面的代码只会更新我购物车的最后一个条目。我在循环中有点挣扎,我只是卡住了。

 if (isset($_POST['quantity'])) { // Update quantities in the cart

    foreach ($_POST['quantity'] as $k => $qty) {  //Full name on form: name="quantity[' . $row['prodid'] . ']"

        $pid = $_POST ['prodid'];
        $sp_type = $_POST ['cat'];

        if (isset($sp_type, $pid)) {
             // Determine the quantity:
             $qty = (filter_var($qty, FILTER_VALIDATE_INT, array('min_range' => 0)) !== false) ? $qty : 1;

             // Update the quantity in the cart:
             $r = mysqli_query($dbc, "CALL update_cart('$uid', '$sp_type', $pid, $qty)");
        }

    } // End of FOREACH 
}

cart.html 上的代码:

这是购物车 html 表单的代码:

<input type="hidden" name="prodid[' . $row['prodid'] . ']" value="' .$row ['prodid'] .'" /></td>
        <td align="center"><input type="text" name="quantity[' . $row['prodid'] . ']" value="' . $row['quantity'] . '" size="2" class="small" /></td>
        <td align="right">£' . $price . '</td>
        <td align="right">£' . number_format($subtotal, 2) . '</td>
        <td align="right"><a href="/wishlist.php?id=' . $row['prodid'] . '&action=move&qty=' . $row['quantity'] .'&cat=' .$row ['cat_id'] .'">

【问题讨论】:

  • 你有一个数量循环但不是prodid,我会重新排列我的表单元素名称以更好地适应循环。例如,类似于:name="quantity[$prodid]" 因此该数量的键成为产品 id
  • 你能提供一个你的 $_POST 参数的 var_dump 吗?
  • 我到底是怎么做的??抱歉,我是初学者(自学)。
  • 一目了然,我敢打赌您没有将输入命名为数组。示例:
  • 我在购物车表单中有 2 个输入(隐藏):“prodid”和 2:类别的“cat”。 prodid 是产品 ID。你可能有一点,上面的名字没有任何 id,例如名称="prodid" 不是名称"prodid[]"

标签: php shopping-cart


【解决方案1】:

将 ID 添加到表单中的所有输入之后。 我在上面的代码中添加了以下内容,它可以工作了!!

        foreach ($_POST['prodid'] as $id=>$prod){
            if ($id==$k){
                $pid = $prod;
            }
        }
        foreach ($_POST['cat'] as $catid=>$cat){
            if ($catid==$k){
                $sp_type = $cat;
            }
        }

其余代码...

【讨论】: