Reputation:
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?
Upvotes: 1
Views: 6356
Reputation: 562
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 */
}
Upvotes: 1
Reputation: 3815
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.
Upvotes: 0
Reputation: 193
you could loop over all parts of the `$_POST array;
foreach($_POST as $key => $value){
//$key contains the name of the field
}
Upvotes: 0
Reputation: 151
You can iterate over all $_POST keys like this.
foreach($_POST as $key => $value)
{
echo $key.": ".$value;
}
Upvotes: 1
Reputation:
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.
Upvotes: 5