I\'m attempting to create a sort of marketplace. Each item on the market has a type (i.e. the item being sold), a value, a quantity, a seller name, and an id, and all of thi
My problem is that since each input field is the result of a while loop of unknown iterations, I can't simply hard code a name into each field. I've tried using a counter variable to keep track and make names, but it doesn't seem to be working.
Name your inputs like this:
<input type="text" name="myName[]" />
<input type="text" name="myName[]" />
<input type="text" name="myName[]" />
Then, in your PHP, $_POST['myName']
or $_GET['myName']
is an array.
This is documented here.
On a related note, in order for the program to work, each field needs to send two values - the id (which I can use to look up the rest of the entry's values) and the quantity that the user wishes to purchase. I've been doing this with a hidden field before the input quantity field.
Sounds fine to me.
For the first problem, simple. Do:
for ($i = 0; $i < sizeOf($returnedSQLarray); $i++) {
//your display code
....
....
echo("<input name='quantity-$i'>");
}
although I still am having trouble imagining why you can't use the product's ID in the quantity's name attribute somehow. for()
loops are great for this kind of looping, though, so if this really is the way you need to handle it you're covered.
The hidden input is fine. Pretty standard, even. Anyone who wants to can send your webserver whatever data they want, so you should only really care about serverside security anyway.
To expand on what @Michael has said in his comment, you need to turn the name='id'
into an array, like this (PHP):
echo '<input type="text" name="id[' . $i . ']">'
Where $i
is incremented every loop.
When the form is posted, you can access this array like this:
$_POST['id']['1']
Replacing ['1']
with whatever you want.