1

I am trying to process a form which I don't know ahead of time what the form fields will be. Can this still be done in PHP?

For example I have this html form:

<form method="post" action="process.php">
     <?php get_dynamic_fields(); // this gets all the fields from DB which I don't know ahead of time what they are. ?>
     <input type="submit" name="submit" value="submit" /> 
</form>

And here is what I have in the PHP process file

<?php
if ( isset( $_POST['submit'] ) && $_POST['submit'] === 'submit' ) {
     // process form here but how do I know what field names and such if they are dynamic.
}

?>

Here is a caveat: assuming I can't get the data from the db ahead of time, is there still a way to do this?

1
  • 2
    var_dump($_POST) will show you what you're receiving. You should have SOME way of processing the data, otherwise what's the point of building the form in the first place? Commented Apr 19, 2013 at 16:58

5 Answers 5

5

Sure, just iterate over all the items in the $_POST array:

foreach ($_POST as $key => $value) {
    // Do something with $key and $value
}

Note, your submit button will exist in the array $_POST, so you may want to write some code to handle that.

Sign up to request clarification or add additional context in comments.

3 Comments

So I take it doing it this way I can only sanitize the inputs but can't really know if a certain field is required. So I can't really do validation is that correct?
@Rick: That's dependant on if you're able to get field names and other information from another one of your form building functions.
Ok then it sounds like I have to pull the data out of the db first to check against the submitted inputs...I was trying to avoid that...thanks again!
1

You can iterate over all $_POST keys like this.

foreach($_POST as $key => $value)
{
    echo $key.": ".$value;
}

Comments

1

This will give you the field names used in HTML form.

$field_names = array_keys($_POST);

You can also just iterate through the POST array using

foreach($_POST as $field_name => $field_value) {
    // do what ever you need to do
    /* with the field name  and field value */
}

Comments

0

you could loop over all parts of the `$_POST array;

foreach($_POST as $key => $value){
   //$key contains the name of the field
}

Comments

0

Get the names of the fields from your get_dynamic_fields function and pass them in a hidden input that is always an array with a static name. Then parse it to get the names of the inputs and how many there are.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.