Load POST data into an array

Hello there,

I want to set up a basic shopping cart using php.

I have a table with each row displaying each item, cost, id and a quantity field.

I have one submit button after the table. When the user clicks on the submit button I want to populate a session with an array containing the id and quantity for each item that has a value entered into the quantity field.

I realise I shall have to use a foreach loop, but I’m not quite sure how to do that.

This is what I have so far:


if (isset($_POST['viewOrder']))
{
  session_start();
  $_SESSION['cart'] = array('id', 'quantity');
}

Here’s an excerpt of the generated HTML for the table:


<form id="catalogue" method="post" action=""> 
  <table> 
    <thead> 
      <th>Code</th><th>Item</th><th>Net Price</th><th>Qty</th> 
    </thead> 
    <tbody> 
      <tr> 
        <td colspan = "6">Books</td> 
      </tr> 
      <tr> 
        <td>BK1<input type="hidden" name="id" id="id" value="BK1" /></td> 
        <td>Language for Learning</td> 
        <td class="price">&pound;27.99</td> 
        <td><input type="text" id="quantity" class="quantity" /></td> 
      </tr> 
      <tr> 
        <td>BK1a<input type="hidden" name="id" id="id" value="BK1a" /></td> 
        <td>Language for Learning Stickers</td> 
        <td class="price">&pound;1.75</td> 
        <td><input type="text" id="quantity" class="quantity" /></td> 
      </tr> 
  </table>
<input type="submit" id="viewOrder" value="Continue"/>
</form>

As you can see I have multiple fields named id, but I don’t know how to only select the relevant id fields, since there is nothing actually connecting the ids to their relevant quantity values, except that they are both in the same table row.

I’m not sure how to approach this problem at the moment. Any pointers would be great.

Many thanks,
Mike

If you want to pass an input value to the server using forms, you should set the name attribute to the input element. you can repeat names (e.g. in input elements of type “radio”, and you can pass an array if you end the elements name with “”. Couples of name=value is what the clients send to the server.
Here’s how to use variables from external sources…