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

Recommended Answers

All 3 Replies

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++;
}
commented: 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.

commented: Defninitely a new method. I need to look more into arrays for my projects. +1

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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.