Jump to content

Capturing all form fields on submit


skyer2000

Recommended Posts

I've been creating a form builder and just hit a snag towards the end.

 

Since the form is dynamically created, there will always be different amounts of fields on every form. On submit, what is the best way to capture the data when the amount of fields (and names) are different everytime? What would be ideal is if there is some sort of code that captures ALL fields, and assigns them as variables.

 

Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/95663-capturing-all-form-fields-on-submit/
Share on other sites

Both $_POST and $_GET (and $_FILES) are already arrays. You can use a foreach() loop to iterate through all the elements (and if you expect that any element can be an array itself, you can use the is_array() function to detect them and use a nested foreach() loop.)

 

There is also no need to assign each and every element to another variable, just use the $_POST and $_GET array variables directly (especially in a generic form script.)

The only safe way to do this is by storing all the names in an array, and checking against that array.

 

You can use

foreach ($_POST as $name => $value) {
   echo $name . ' = ' . $value . '<br>';
}

 

But POST elements are defined by the user... if they so choose, they can add any element by any name they wish, and pass it to your $_POST array.

 

So i'd do something like this

 


$elements = array ('firstname', 'lastname', 'email', birthday');

foreach ($_POST as $name => $value) {
   if (in_array($name, $elements) )
      echo $name . ' = ' . $value . '<br>';
}

Trying to figure this out, since I'm pulling form a database, this is what I have right now...

 

$elements = mysql_fetch_array(mysql_query("SELECT id FROM foo"));

foreach ($_POST as $name => $value) {
   if (in_array($name, $elements) )
      echo $name . ' = ' . $value . '<br>';
}

Ok I got it, changed it around into something I understand more

 

$fields = mysql_query("SELECT id FROM foo");

while($field_info = mysql_fetch_array($fields))
{
	$fieldname = $field_info['id'];

	$fieldid = mysql_real_escape_string($_POST[$fieldname]);

	echo "$fieldid<br>";
}

 

Thanks for the replies though, they guided me into the right direction!

 

edit: where did the topic solved button go??

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.