skyer2000 Posted March 11, 2008 Share Posted March 11, 2008 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? Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted March 11, 2008 Share Posted March 11, 2008 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.) Quote Link to comment Share on other sites More sharing options...
discomatt Posted March 11, 2008 Share Posted March 11, 2008 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>'; } Quote Link to comment Share on other sites More sharing options...
skyer2000 Posted March 11, 2008 Author Share Posted March 11, 2008 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>'; } Quote Link to comment Share on other sites More sharing options...
skyer2000 Posted March 11, 2008 Author Share Posted March 11, 2008 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?? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.