views:

37

answers:

2

To begin with, i should clarify the title, so you really understand what I'm trying to do.

I'm working on a shopping-cart-ish script, but it's a little different because all products (almost always) will be purchased each time. Therefore i believe it's best to list all of the items up with a table, and then let the customer choose the amount of each product they want.

It'd look something like this:

-- Name ------------------------- Amount --
-- A random product ------------- 15 ------
-- Another random product ------- 2 -------
-- And a third one --- ---------- 19 ------
-- ------------------------------ ---------
-- ------------------------------ SUBMIT --

The problem is, I'm not sure how to write it into the database. Or more specific, i don't know how to submit the data in a way that i get all of the chosen products, as well as the amount of each one into an array. I might add more products to the database later, so i can't hardcode it in.

I can't post two values in one input, which is too bad. If i could do that i could post the ID and the amount as two different values.

Any ideas how to do this?

A: 

concatenate the productID and the qty with a pipe "|" so it would be

productId=14

Qty= 3

inserted value= 14|3

then after your db fetch, you can explode the data by the "|" and have part1=14 and part2=3

FatherStorm
I thought of that aswell, but that wouldn't really look good. And i would have to instruct the users to put the ID of the product first etc, heh. Any more ideas?
Nike
-1. convoluted (and breakable) solution to the problem
Wrikken
+1  A: 

When you create your input fields, use an array for the name, with the product id as the key.

For example (where $product_id is the ID of the product that the amount corresponds to):

<input type="text" name="amounts[<?=$product_id?>]">

Then in PHP, after the form is posted, $_POST['amounts'] will be an array, where the keys are the product IDs, and the values are the actual amounts. You do not need to do anything special for this to happen; by default, PHP will recognize that GET/POST data that contains []s should be made into an array.

Then you can just iterate over this array to update the database:

foreach ($_POST['amounts'] as $product_id => $amount)
{
  if (!empty($amount)) // was a value given for this amount?
  {
    // build your insert query here
  }
}
Daniel Vandersluis
Thanks a lot! I'm too tired to implement that now, i'm actually heading to bed now. But i'll give it a shot tomorrow, and comment back.
Nike
+1, the most easy (php-)way to get the data without cumbersome string manipulation.
Wrikken
Got it working like a charm, thanks for the help. :)
Nike