tags:

views:

106

answers:

2

Hi

I'm making a web page in which I have a list of products, along with a field next to each product in which a customer is meant to enter the quantity they want to order. The list of products is generated from a database and therefore the number of products isn't known. Is there a way of POSTing the quantity of each product ordered along with the IDs (from the database) of each product?

Thanks

Ben

A: 

The correct method is for the database to track the number of elements it emits and store a hidden field.

If you can't do this, you can yourself build some javascript into the page which, upon submit, will count the number of elements in the page and set the value of a hidden field in the form to hold this value.

Blank Xavier
+6  A: 

You can create form fields with array notation, for example:

<input type="text" name="quantity[productid]">

So you could dynamically generate some fields in your form like this:

<input type="text" name="quantity[3]">
<input type="text" name="quantity[4]">
<input type="text" name="quantity[2]">

And then in PHP it will become an array you can loop over easily:

foreach ($_POST['quantity'] as $productId => $quantity) {
    echo (int) $productId . ':' . (int) $quantity;
    //etc.
}
Tom Haigh