Dynamic Form Processing

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hybernate20
Forum Newbie
Posts: 2
Joined: Wed May 20, 2009 7:34 am

Dynamic Form Processing

Post by hybernate20 »

Hello. I've been working on a project for a little while, and I've hit a bit of a wall here.

I have a page that has a form on it. Using Javascript, the user can add as many fields as they need to a certain section. The input fields are dynamically named with a counter variable, so they will be like "field0", "field1", field2" etc. depending on how many the user adds. How can I process this with PHP? What is getting me is the fact that I don't know how many fields there will be, and I don't know how to find out on the fly with PHP... any ideas?

Sorry if I'm being vague here...

Thanks,
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Dynamic Form Processing

Post by onion2k »

What you asked for:

Code: Select all

foreach ($_POST as $key => $value) {
  if (strpos($key,"field")===0) {
    $key = str_replace("field","",$key);
    echo $key."-".$value;
    echo "<br />";
  }
}
However, it'd be better to add the fields with a name of "field[]" instead, that way they'll be an array in $_POST instead. Much easier to use.
hybernate20
Forum Newbie
Posts: 2
Joined: Wed May 20, 2009 7:34 am

Re: Dynamic Form Processing

Post by hybernate20 »

Thanks! You are right, it would make much more sense to just make myself an array in POST. This was very helpful, thanks for your advice!
Post Reply