Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

php - Forms with a variable number of fields

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 this information is stored in a MySQL database.

When the user views the market, all entries in the market are returned. In addition, an input text field appears at the end of each entry. The user can enter any number between leaving it blank (0) and the max quantity available.

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. For example: name='.$i++.'

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. I'm not sure if this is a good way of going about this, but I should note that there's no need as far as I can tell for the id to be kept secret.

Just so everything's clear, here's a basic UI mockup: http://img850.imageshack.us/img850/2654/marketui.jpg

Note that the column starting with consists of user inputted values (i.e. the 100s are the values of user-inputted text fields). The hitch is that while there are 2 rows in this example, the actual number is not deterministic, and so I can't hard code names for each input field.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...