Search code examples
phphtmlformsshopping-cart

Update shopping cart with more variants


I am currently trying to create shopping cart and send it throught $_SESSION variable.

But when I try to update items via $_POST, it only updates the last product in cart.

Here is my form

<form method="post">
<?php foreach ($_SESSION['cart'] as $product) { 
$productDetail = Products::getProduct($product['id']);
?>
<input type="hidden" name="id" value="<?= $product['id']; ?>">
<input name="qty" size="5" maxlength="50" type="text" value="<?= $product['quantity']; ?>">
<input name="width" size="5" maxlength="50" type="text" value="<?= $product['width']; ?>">
<input name="length" size="5" maxlength="5" type="text" value="<?= $product['length']; ?>">
<?php } ?>
<input type="submit" value="send" />
</form>

Here how i update my cart

$item_id = $data['id'];
$quantity = $data['qty'];
$width = $data['width'];
$length = $data['length'];

$_SESSION['cart'][$item_id]['quantity'] = $quantity;
$_SESSION['cart'][$item_id]['width'] = $width;
$_SESSION['cart'][$item_id]['length'] = $length;

It always updates only the last one in form.

Is there some or better solution to this problem? I would very appriciate it.

Thank you.


Solution

  • You need to add [] to input names to get arrays in $_POST values:

    <form method="post">
    <?php foreach ($_SESSION['cart'] as $product) { 
    $productDetail = Products::getProduct($product['id']);
    ?>
    <input type="hidden" name="id[]" value="<?= $product['id']; ?>">
    <input name="qty[]" size="5" maxlength="50" type="text" value="<?= $product['quantity']; ?>">
    <input name="width[]" size="5" maxlength="50" type="text" value="<?= $product['width']; ?>">
    <input name="length[]" size="5" maxlength="5" type="text" value="<?= $product['length']; ?>">
    <?php } ?>
    <input type="submit" value="send" />
    </form>
    

    Then you can iterate over $data['id'] array (I assume here that it is the same as $_POST['id']), taking advantage from the fact that those 4 arrays have the same corresponding key for given data set:

    $item_ids = $data['id'];
    $quantitys = $data['qty'];
    $widths = $data['width'];
    $lengths = $data['length'];
    
    foreach($item_ids as $k=>$item_id){
        $_SESSION['cart'][$item_id]['quantity'] = $quantitys[$k];
        $_SESSION['cart'][$item_id]['width'] = $widths[$k];
        $_SESSION['cart'][$item_id]['length'] = $lengths[$k];
    }