0

Hello, I am working on a website where the user can fill out a long form. For simplicity reasons, a part asks them to list features they would like to see. For that I plugged in some javascript to make a "[more]" link to add more form fields. Each form field is given a name like feature1, feature2, and so on, depending on how many times they clicked it. Anyways, how would I process that in PHP to make it all go into one row inside my database? How would I tell it to process and group all those fields.Remember, the only difference between those fields is the number at the end

3
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by epicrevolt
1

In the program that processes the form you will still see them as individual fields. When you have an unknown number of fields, the best way to handle it is to have a standard field name followed by an index number (as you are doing). In the receiving program, you can check if the variables exist and then concatenate them before you save them to the database. In this example, I separated the values with commas. That would allow you to explode them to process them as individual fields later. You should do some editing on the incoming fields before you save them. if you use a separator, you'll need to check that it isn't in any of the strings.

$features = "";
$i = 1;

while (isset($_POST[feature$i])) {
      $features .=  $_POST[features$i].","; 
      $i++;
}

Edited by chrishea: n/a

Votes + Comments
Solved my problem, I love you :)
1

In my opinion the best way to do this would be to name your fields using an array index.

<input name="field[]" type="text" size="20" maxlength="40" />
<input name="field[]" type="text" size="20" maxlength="40" />
<input name="field[]" type="text" size="20" maxlength="40" />

Then when you process the fields with PHP it is as simple as:

<?php
foreach( $_POST['field'] as $field ){
  //Do something with the value of $field.
}

No counter needed, will scale to an infinite size, and $_POST will be a numerically indexed array of values that were submitted so you can iterate over it with any of the array functions etc.

Votes + Comments
Defninitely a new method. I need to look more into arrays for my projects.
0

Thank you guys! The first one will fit right in my code right now, but the second one I will look into. It seems more efficient. I would have never thought of that.

This is why website designers need you :)

(I mainly design, but can do simple PHP CMS stuff too)

Edited by epicrevolt: More Thanks!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.