Top Menu

To update the quantity of multiple items in a cart using a form in PHP, you can create a form with a text input field for the quantity and a hidden input field for the item ID for each item in the cart, and then submit the form to a PHP script that updates the cart based on the form input.

Here’s an example of how you could do that:

HTML form code:

<form action="update_cart.php" method="post">
    <?php foreach ($cart as $item): ?>
    <label>Quantity for <?php echo $item['name']; ?>:</label>
    <input type="number" name="quantity[<?php echo $item['id']; ?>]" value="<?php echo $item['quantity']; ?>">
    <input type="hidden" name="item_id[]" value="<?php echo $item['id']; ?>">
    <?php endforeach; ?>
    <input type="submit" value="Update">
</form>

In this example, we’re using a PHP loop to generate the form input fields for each item in the cart. For each item, we have a text input field named quantity where the user can enter the new quantity, and a hidden input field named item_id that holds the ID of the item in the cart that should be updated. We use the [] syntax in the name attribute of the quantity field to indicate that it should be an array with keys corresponding to the item IDs.

The form is submitted to a PHP script named update_cart.php when the user clicks the “Update” button.

PHP script code:

<?php
// start the session and get the cart from the session
session_start();
$cart = $_SESSION['cart'];

// loop through the form input and update the cart with the new quantities
foreach ($_POST['quantity'] as $item_id => $quantity) {
    foreach ($cart as &$item) {
        if ($item['id'] == $item_id) {
            $item['quantity'] = $quantity;
            break;
        }
    }
}

// save the updated cart to the session and redirect back to the cart page
$_SESSION['cart'] = $cart;
header('Location: cart.php');
?>

About The Author

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Close