0

I am building a simple cart with a while loop. I am showing product ID and Quantity. The user can change the quantity, and I want a single "UPDATE" button at the bottom of the cart that will update foreach of the items in the cart. It needs to pull the product ID and the new quantity entered by the user. How can I do this.

I can do it for a single cart item, but I can't figure out how to pass the multiple items as an array and treat the data once the UPDATE button is pressed.

My code:

<?
$data = mysql_query(.............);

if (isset($_POST['update'])) 
{   
    foreach ($array as $id => $qty) 
    {   
        $product_id = ...??..;
        $new_qty = = ...??..;

        $sql = "INSERT INTO.....".$product_id." and.... ".$new_qty."...  ";

        $insert = mysql_query($sql);
    }
}
?>



<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" > 

    <?
    while ($data2 = mysql_fetch_array( $data)) { ?> 

        QTY: <input type="number" name="qty" class="form-field" value="<?=$data2['qty']?>" >
        <input name="products_id" value="<?=$data2['product_id']?>" type="hidden">

    <? } ?>

    <input class="submit-button" type="submit" name="update" value="UPDATE QTY" />

</form>
user3011784
  • 833
  • 1
  • 8
  • 30

2 Answers2

0

You have to assign name attribute with square brackets to indicate array for your form elements.

Look here for explanation: here

Look here for simple concept example and alter it to suit your code: here

Community
  • 1
  • 1
dchayka
  • 1,291
  • 12
  • 20
0
<?
    while ($data2 = mysql_fetch_array( $data)) { ?> 

        QTY: <input type="number" name="qty[]" class="form-field" value="<?=$data2['qty']?>" >
        <input name="products_id[]" value="<?=$data2['product_id']?>" type="hidden">

    <? } ?>

then

if (isset($_POST['update'])) 
{   
    $array = $_POST['products_id'];
    $quantities = $_POST['qty'];
    foreach ($array as $key => $id) 
    {   
        $product_id = $id;
        $new_qty = = $quantities[$key];

        $sql = "INSERT INTO.....".$product_id." and.... ".$new_qty."...  ";

        $insert = mysql_query($sql);
    }
}
Atiqur
  • 3,802
  • 1
  • 25
  • 26