benwad
benwad

Reputation: 6594

POSTing an arbitrary number of records from an HTML form

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

Upvotes: 3

Views: 531

Answers (2)

Tom Haigh
Tom Haigh

Reputation: 57815

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.
}

Upvotes: 8

user82238
user82238

Reputation:

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.

Upvotes: 0

Related Questions