0

I've got a bunch of <input type='text' name='input0' /> fields.

The user can add them dynamically so we'd get something like:

<input type='text' name='input0' />
<input type='text' name='input1' />
<input type='text' name='input2' />

...etc. We don't know how many there will be in total. When the form gets submitted, I want to loop through each of these input fields and assign them to a $_POST variable. These are NOT the only input fields in the form, there are other elements such as radio buttons, checkboxes and other text fields. My problem is I need to somehow identify these particular dynamically-generated text fields, and loop through them. How can I do this, when all I get on the server side are the names of the input fields?

Charles
  • 50,943
  • 13
  • 104
  • 142
Allen S
  • 3,471
  • 4
  • 34
  • 46

1 Answers1

6

Use:

<input type='text' name='input[]' />

then you can:

foreach($_POST['input'] as $input){
    echo $input;
}
Prisoner
  • 27,391
  • 11
  • 73
  • 102
  • Thanks! Marking as answer in ETA 11 mins – Allen S Nov 21 '13 at 11:29
  • One more (remotely related) question: If I'm recording each value in a MySQL DB, is it best to insert the query into the `foreach` loop so it's recorded with each iteration? Seems like it would take forever if there are 50 input fields. Or is there a more efficient way of recording all values with one query? – Allen S Nov 21 '13 at 11:40
  • @user1775598 if you're inserting them into a database, you can build a multi-valued `insert` statement, like this: http://stackoverflow.com/questions/1307618/multiple-mysql-insert-statements-in-one-query-php then just execute it once you've finished your loop. Make sure you don't leave yourself open to mysql injections though! – Prisoner Nov 21 '13 at 12:08