How can I set up a system that reads $_POST data that comes from a form with a user-decided number of inputs? Can I use an index such as $_POST[1] or something similar? (e.g. create/remove pages, submit changes and process an input for as many pages as the user decides they want)
问题:
回答1:
In your form create your input variables with names ending in square brackets:
<input name="lines[]" type="text"><br>
<input name="lines[]" type="text"><br>
<input name="lines[]" type="text"><br>
You can add as many as you need, or creat them on the fly in javascript.
When the form is submitted the data will appear as an array in $_POST:
echo $_POST['lines'][0];
echo $_POST['lines'][1];
echo $_POST['lines'][2];
回答2:
You should do something like this:
foreach($_POST as $k => $v){
// The action you want to perform for each input
}
To make a more advanced solution, I think, we need a bit more information about what exactly it is, you want to achieve :)
回答3:
You can create an array of fields using a name such as, variables[], then loop through them with a foreach loop.
Setting the variable with the square brackets sets it as an array which allows you to loop through them. If you need variable names you could pass them dynamically by writing them in the square brackets. EG:
<input type="text" name="variables[variableName-one]" />
<input type="text" name="variables[variableName-two]" />
The benefit of using this method is you can use the array key names (variableName-one etc.) in your code by setting the key in the foreach loop. Similar to:
foreach($_POST['variables'] as $variableName => $variable){
echo $variableName.' was set as '.$variable;
}
Otherwise you can leave it blank and you can access them as the number eg:
$_POST['variables'][1]
回答4:
I don't know if i understood your question completely
foreach ($_POST as $key=>$value) {
doSomething($key,$value);
}
Where in $key you found the input name and in $value its value. Of course you cannot generalize that too much. For example if there is checkbox and that checkbox doesn't get checked you won't get it in the post array.
if you have some inputs with array like name : you will get them as an array.
foreach ($_POST as $key=>$value) {
if(is_array($value)){
foreach($value as $key2=>$value2){
doSomethingOther($key,$key2,$value2);
}
} else {
doSomething($key,$value);
}
}
But this way you should write very specific code for any input you can get. Or you have to find way to codify input name so they give you hint on what you have to do with them And maybe you expose yourself to some risk of hijacking if you accept all possible inputs one user can send you.