PHP How to process a form that has dynamically generated fields? - php

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?

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.

You can iterate over all $_POST keys like this.
foreach($_POST as $key => $value)
{
echo $key.": ".$value;
}

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 */
}

you could loop over all parts of the `$_POST array;
foreach($_POST as $key => $value){
//$key contains the name of the field
}

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.

Related

How can I handle a $_POST variable identifier as a variable?

Re-writing the question here so it's (hopefully) easier to understand.
I have a piece php that received a $_POST from a form. Each time a $_POST is completed, only one set of data is sent. It could be $_$POST['boat'] or $_POST['car'] or $_POST['dog'] etc. I do not know what the post will contain upon receiving it. If it is $_POST['dog'] then the value of the post will go into the $database.dog table. If it is $_POST['car'] then the value of the post will head into the $database.car table, and so on.
Once a post is made, how can I identify whether the post was called 'car' or 'dog' or 'boat' or anything else ?
There's a lot of ways to do this. Simply with ifs:
if(isset($_POST['car'])) {
// do car stuff
}
if(isset($_POST['boat'])) {
// do boat stuff
}
//etc...
Or a switch:
switch(true) {
case(isset($_POST['car'])):
// do car stuff
break;
case(isset($_POST['boat'])):
// do boat stuff
break;
//etc...
}
To avoid the ifs or switch you can use a hidden input:
<input type="hidden" name="form" value="car">
Then use $_POST['form'] to dynamically build your queries etc...
If car or boat etc... is the only key under $_POST or if it is always the first key then:
$form = key($_POST);
You can get the key/index and value and print that info if you are unsure what the keys or values will be that are coming from your form POST.
function getKeyValuePairs() {
$stmt = null;
if(isset($_POST)){
foreach($_POST as $key => $value) {
$stmt .= $key." => ".$value."<br>";
}
print_r($stmt);
}
Because $_POST is global no need to push variable into function.
HTML: run function to print key/value pairs
<div>
<?php echo getKeyValuePairs(); ?>
</div>

Is there any way to get ONLY the selects inputs from a form?

I need to get the name and value from many selects with POST, like this:
foreach ($_POST as $key => $value) {
// do stuff
}
The problem is I have other input types in this same form, like a checkbox, for example. I want to get in this foreach only the selects (I can't call by name cuz' each select have one name)
I guess if all your parameters are in an array yes you can, for example, in your HTML you have something like :
<input type="text" name="data['first_name']" value="something"/>
<input type="text" name="data['last_name']" value="somethingElse"/>
in your PHP code, you can use a foreach like so :
foreach( $_POST['data'] as $data )
{
var_dump($data);
}
The input element types are not sent to the server with your POST data. Only the names and values are.
The only way to differentiate would be to send additional data, such as a list, or by naming the inputs differently.
Really though, you shouldn't be POSTing data that you don't care about anyway. Save bandwidth, hide the elements that go nowhere with JavaScript on POST.
Only way to do that server side is to know exactly which inputs are selects and iterate through these.
$selects = array('select1', 'select2', ...);
foreach ($selects as $select) {
$value = $_POST[$select];
// do stuff
}
If you know the name of the select inside form you can do this
Your HTML:
<form>
<select name='selectName1'>
<option value='xx'>xx</option>
<option value='xx'>xx</option>
</select>
<select name='selectName2'>
<option value='xx'>xx</option>
<option value='xx'>xx</option>
</select>
</form>
Your PHP code
$arraySelect = array('selectName1', 'selectName2', ...);
foreach($_POST as $key=>$value)
if(in_array($key, $arraySelect))
$$key = $value; //this will create a variable with the name you use, in this case $selectName1, $selectName2. And the option the user selected will be assigned.

how NOT to store submit button value as post data php

ok i have dynamically created form elements with unique names and when validated i want to store all the form data into SESSION.
This is the code to do it:
if(isset($_POST["address_submit"])){
insertSessionVars();
header("Location: http://localhost/project%20gallery/notes.php");
exit;
}
function insertSessionVars(){
foreach($_POST as $fieldname => $fieldvalue){
$_SESSION['formAddresses'][$fieldname] = $fieldvalue;
}
}
This works almost fine but stores also submit button value. I output it like this:
foreach($_SESSION['formAddresses'] as $value){
echo $value;
}
Any help will be greatful :)
Don't assign a name attribute to your submit button. If you assign a name then it is passed as part of the $_POST array.
<input type="submit" value="My Button" />
Since you no longer have the submit button in post, instead of checking if the submit button is set check to see if the post array contains data using count().
if(count($_POST) > 0)
The $_POST values are just array so after the for each why don't you use unset to drop the submit key from the array
That way you can check the form has been submitted and the either choose to not set the submit key or drop it rather then not giving it a name at all
Either way you can in your foreach do something like this (see *) and pass "$except" as parameter.
Where $except has to be the name of your submit button in insertSessionVars();
if(!in_array($key, $except)){...}
And ofc above your foreach something like this :
if(!is_array($except)) $except=array($except);

php form multiple input

I have a PHP page with a list of items pulled from a database. Each item has an input form next to it, and right at the bottom, a submit button.
How can i do a POST check to find out which inputs have had data added? I can get the data, but how do I know the names of the particular inputs that have been filled?
Iterate over $_POST and list the keys which have nonempty values.
foreach ($_POST as $key => $value) {
if (!empty($value)) {
echo $key . " was filled in.";
}
}
Take a look at the isset() function of PHP - http://php.net/manual/en/function.isset.php.
For Example,
<?php
if(isset($_POST['somevar'])) {
// if the value has been set, this code is executed
} else {
//value not set, so execute this code.
}
?>

php form result loop

I'm trying to make a BASIC roulette script.
Is there anyway to get the submitted results of a form using PHP? In fact I know theres a way, but i can't find out how to do it.
So say if my form had several fields I want the result to loop through and show me which fields were filled and the numbers in each.
UPDATE: And say the form has about 40 fields, would I have to name each one in the loop? Any easier way?
$_GET or $_POST depending on the form method.
if(isset($_REQUEST['formInputName'])){
echo $_REQUEST['formInputName'];
}
$_REQUEST looks for GET, POST, and COOKIE.
You can also use $_GET to get a variable from the url (asdf.php?var=2).
If your form looks like this:
<form method="post" action="result.php">
<input type="text" name="foo">
</form>
In result.php you can use the global variable $_POST and loop through it if you want:
foreach($_POST as $name => $value) {
echo $name . ' = ' . $value;
}
If your form has 40 fields, you still need to name them all, but you can automate the process of naming and retrieving them with a loop. For example, if you wanted to create a sum with the value of all the fields, you could name them number1, number2, etc and do:
$sum = 0;
for($i = 1; $i <= 40; $i++)
$sum += $_POST['number' . $i];
You need to define the name of each field using name="something" in the input element, and than in the PHP you're getting it using $_POST['something'] in case you sent the form as method="post" or $_GET['something'] in case of get method
You can see what's sent using var_dump() or print_r(), just write something like that:
echo '<pre>';
print_r($_POST);
Or you can go all over the array using foreach statement:
<?php
foreach($_POST AS $key=>$val)
{
echo $key.': '.$val."<br />\n";
}
?>

Categories