Pass selected form input to backend - php

Consider a simple HTML form like
<form>
<div>
<input type='checkbox' name='selections[]' value='1' />
<input type='text' name="inputs[]" value='' />
</div>
<div>
<input type='checkbox' name='selections[]' value='2' />
<input type='text' name="inputs[]" value='' />
</div>
<div>
<input type='checkbox' name='selections[]' value='3' />
<input type='text' name="inputs[]" value='' />
</div>
</form>
There are three rows, assume only the 2nd, 3rd rows are checked, and all three text inputs are filled with (a, b, c), so in my backend (PHP), I can have two arrays
e.g.
$selections = array(2, 3);
$inputs = array('a', 'b', 'c');
What is the easy way to remove a from the $inputs since the checkbox is not checked? i.e. So I can loop the two arrays more easily.

I'd probably use array_map
$inputs = array_map(function($v) use ($inputs) {
return $inputs[$v - 1];
}, $selections);
Though MingShun's answer will work fine if converted to PHP

You should change your HTML like this:
<form method="post">
<div>
<input type='checkbox' name='data[0][selections]' value='1' />
<input type='text' name="data[0][inputs]" value='' />
</div>
<div>
<input type='checkbox' name='data[1][selections]' value='2' />
<input type='text' name="data[1][inputs]" value='' />
</div>
<div>
<input type='checkbox' name='data[2][selections]' value='3' />
<input type='text' name="data[2][inputs]" value='' />
</div>
<input type="submit"/>
TEST DATA:
<?php
echo '<pre>';
print_r($_POST['data']);
?>
RESULT:
Array
(
[0] => Array
(
[selections] => 1
[inputs] => 1
)
[1] => Array
(
[selections] => 2
[inputs] => 2
)
[2] => Array
(
[selections] => 3
[inputs] => 3
)
)
OR:
Array
(
[0] => Array
(
[inputs] => 1
)
[1] => Array
(
[selections] => 2
[inputs] => 2
)
[2] => Array
(
[selections] => 3
[inputs] => 3
)
)
Now you can loop result and handle.
$selections = array();
$inputs = array();
foreach ($_POST['data'] as $item){
if (!empty($item['selections']) && !empty($item['inputs'])){
$selections[] = $item['selections'];
$inputs[] = $item['inputs'];
}
}
var_dump($selections);
var_dump($inputs);

This answer requires detailed knowledge of what's coming in. Which is rather bad if you want to reuse it.
The following assumptions are being made about the html page:
The row values start from 1
The row values are ascending
The row values are continuous. e.g. 1, 2, 3... not 1, 2, 4...
And here's the code:
$len = count($selections);
for ($i = 0; $i < $len; $i++)
{
if (!in_array($i + 1, $selections))
unset($inputs[$i]);
}

Related

php inserting multiple radio values with same name

I'm trying to insert multiple values using radio, here is my example:
<input type="radio" name="toppingPrice[]" value="<?= $topping['name'];?>-<?= $topping['price'];?>">
this one work if I insert single input, but if I want to insert more than one for example:
Size: small, medium, large <- name="toppingPrice[]" for all input values
Cheese: yes, no <- name="toppingPrice[]" for all input values
Level: spicy, normal <- name="toppingPrice[]" for all input values
this will not work because it will merge into 1 group so if I have to choose only one of all toppings.
my original code looks like:
foreach ($toppingPrice as $key) {
list($toppingName,$toppingNameEn, $toppingPrice) = explode("-",$key,3);
$tName[] = $toppingName;
$tNameEn[] = $toppingNameEn;
$tPrice += $toppingPrice;
}
$tn = implode(",", $tName);
$tn_en = implode(",", $tNameEn);
$price = $price + $tPrice;
Html:
<input type="checkbox" name="toppingPrice[]" id="<?= $topping[0];?>" value="<?= $topping['name'];?>-<?= $topping['name_en'];?>-<?= $topping['price'];?>" <? if($topping['price'] < 1){echo "checked";}?>>
I hope I delivered the question in the right way
please give me any idea or solution for fix this issue
You should use name attribute as shown in below code.
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
<form name="test" method="post">
<input type="radio" name="toppingPrice.size[]" value="1"> 1
<input type="radio" name="toppingPrice.size[]" value="2"> 2
<input type="radio" name="toppingPrice.size[]" value="3"> 3
<br>
<input type="radio" name="toppingPrice.toping[]" value="4"> 4
<input type="radio" name="toppingPrice.toping[]" value="5"> 5
<input type="radio" name="toppingPrice.toping[]" value="6"> 6
<br>
<input type="radio" name="toppingPrice.level[]" value="7"> 7
<input type="radio" name="toppingPrice.level[]" value="8"> 8
<input type="radio" name="toppingPrice.level[]" value="9"> 9
<button type="submit" value="save" /> Save
</form>
This will be your $_POST after form submit
Array
(
[toppingPrice_size] => Array
(
[0] => 1
)
[toppingPrice_toping] => Array
(
[0] => 5
)
[toppingPrice_level] => Array
(
[0] => 9
)
)

Get value of input where checkbox[] is checked

I've a problem, i need to get a value of an input (text) when his checkbox is selected.
<form method=GET>
<input type =checkbox name = checkbox[]>
<input type = 'text' name=? >
<input type =checkbox name = checkbox[]>
<input type ='text' name=? >
<input type =checkbox name = checkbox[]>
<input type = 'text' name=? >
<input type = 'submit' name='Submit' >
</form>
This is what I want excactly
If(checkbox == checked)
{
Echo the entered input text value
}
Thanks inadvance.
Checkbox and radio type field does not get submit when they are not checked or selected.
So you need to check the get/request object whether checkbox name is there or not in the object.
Like
if(isset($_GET['checkbox'])){
}
When you check checkbox you can get value of next input box.
$("input:checkbox").change(function(){
if(this.checked){
alert($(this).next("input").val());
}
});
Demo
I am assuming you meant after submission to a PHP script.
I just threw this together and have not tested it yet, but looks fairly straight forward.
It will also work with <input type=checkbox name="c[]">, but just a little apprehensive about the text and checkbox synchronization with the array.
HTML
<form action="./chkbx.php" method=GET>
<input type=checkbox name="c1" value="1"/>
<input type="text" name="t1" />
<input type=checkbox name="c2" value="2"/>
<input type="text" name="t2" />
<input type=checkbox name="c3" value="3"/>
<input type="text" name="t3" >
<input type="submit" name='Submit' />
</form>
PHP
foreach ($_GET as $key => $val){
$chk[substr($key,0,1)] = intval(substr($key,1,1));
$txt[substr($key,0,1)][intval(substr($key,1,1))] = $val;
}
echo '<h2>Text=' . $txt['t'][$chk['c']] . '<h2>';
Test Code
<?php
echo <<<EOT
<!DOCTYPE html>
<html lang="en"><head><title>Menu Test</title><meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style type="text/css">
</style></head><body>
<form action="./chkbx.php" method=GET>
<input type=checkbox name="c1" value="1"/>
<input type="text" name="t1" />
<input type=checkbox name="c2" value="2"/>
<input type="text" name="t2" />
<input type=checkbox name="c3" value="3"/>
<input type="text" name="t3" >
<input type="submit" name='Submit' />
</form>
EOT;
foreach ($_GET as $key => $val){
$chk[substr($key,0,1)] = intval(substr($key,1,1));
$txt[substr($key,0,1)][intval(substr($key,1,1))] = $val;
}
echo '<h2>' . $txt['t'][$chk['c']] . '<h2>';
echo '<pre>';
var_export($chk);
echo"-------------------\n";
var_export($txt);
echo '</pre></body></html>';
Results:
With checkbox c2 checked and text boxes containing "Text One" "Text Two" "Text Three"
Below output from is the echo '<h2>Text=' . $txt['t'][$chk['c']] . '<h2>';
Text Two
$chk (
't' => 3,
'c' => 2,
'S' => 0,
)-------------------
$txt (
't' =>
array (
1 => 'Text One',
2 => 'Text Two',
3 => 'Text Three',
),
'c' =>
array (
2 => '2',
),
'S' =>
array (
0 => 'Submit',
),
)
Summary:
The submitted check box value is stored in $chk['c']
The submitted Text is in $txt['t'][0], $txt['t'][2], $txt['t'][3] respectfully.
So the text can be retrieved by $txt['t'][$chk['c']
Loop and echo executed in 0.000054 seconds. 54 micro seconds, not too bad.
The value of checkbox only returns boolean (i.e. true of false).
You should use
if(isset($_GET["checkbox"]))
instead of
if(checkbox == checked)

PHP For loop for $_POST

Sorry for the noob question. But I am stuck here.
This is my HTML form where the user-form div can be cloned to as many as possible. The #submit-form div has some hidden values which are common for all.
HTML -
<div class="user-form">
<input type="text" autocomplete="off" name="name[]" >
<input type="email" autocomplete="off" name="mail[]" >
</div>
<div class="user-form">
<input type="text" autocomplete="off" name="name[]" >
<input type="email" autocomplete="off" name="mail[]" >
</div>
<div id="submit-form">
<input type='hidden' name='refer_user_id' value='<?php echo $refer_user_id ?>'>
<input type='hidden' name='refer_user_email' value='<?php echo $refer_user_email ?>'>
<input type="submit" value="Invite" />
<input type="button" class="button" id="clonetrigger" value="Clone" />
</div>
I'm using ajax to submit the form. Basically I want to create accounts using the name and email fields. In PHP How do I use foreach to loop through the name and email fields so that I can create unique accounts?
My print_r($_POST); array looks like this.
Array
(
[name] => Array
(
[0] => david
[1] => Mark
[2] => cindy
)
[mail] => Array
(
[0] => david#abc.com
[1] => mark#abc.com
[2] => cindy#abc.com
)
[refer_user_id] => 2
[$refer_user_email] => test#abc.com
)
Create a loop with a number of iterations equal to the number of submitted name/email pairs, then use the loop counter to access the values for each user.
for ($i = 0; $i < count($_POST['name']); $i++) {
{
$name = $_POST['name'][$i];
$mail = $_POST['mail'][$i];
// Process the new user
}
go through one of the arrays with a foreach, use the key for the second array.
foreach($_POST['name'] as $key =>$name ){
$mail = $_POST[$key];
}
foreach($_POST['name'] as $key => $val) {
echo $val
}
foreach($_POST['mail'] as $key => $val) {
echo $val
}
Easiest way to loop through those elements. You can reference the other elements with $_POST['refer_user_id']. While this works for the purposes of a foreach, the for loop posted above is more efficient, so I'd recommend using it.
http://php.net/manual/en/control-structures.foreach.php More reading on it here.
You can use array_combine function:
$data = array_combine($_POST['name'],$_POST['mail']);
foreach($data as $name=>$mail){
print $name;
//...
}
See array_combine.
You could also use the JavaScript that's auto-generating the form items to give them a name that would result in linking the php object. i.e.
<div class="user-form">
<input type="text" autocomplete="off" name="user[1][name]" />
<input type="email" autocomplete="off" name="user[1][mail]" />
</div>
<div class="user-form">
<input type="text" autocomplete="off" name="user[2][name]" />
<input type="email" autocomplete="off" name="user[2][mail]" />
</div>
Then you could loop through the pairs with foreach($_POST['user'] as $key=>$value) etc...

How to select an array within an array PHP

I am trying to perform some array-ception here: Array within an array. I have a string forms which pass on hidden values to the next form. One of these forms submits an array of checkbox values to another form. That form then submits all previous forms into a database. It's working great except for one problem. When passing the array of checkboxes through another form, it puts the array into another array. I want to select the nested array and store it in a local variable. The array is called interests
Array ( [0] => Array ( [0] => movies [1] => art [2] => cars [3] => business [4] => comedy [5] => technology ) )
Right now my array looks like the array above. When I add [0] to $_POST['interests'] like so:
$int = $_POST['interests'][0];
It successfully stores the second array into the variable int. Problem is that it stores it as a string and not an array. It still looks like an array when I echo it out though
Array ( [0] => movies [1] => art [2] => cars [3] => business [4] => comedy [5] => technology )
How do I store the nested array in a variable. Or how do I turn the above string into an array.
Thank you
If I understood what you mean (and it's a huge if), you might use the following:
Original page:
<form method="POST" ... >
<input type='checkbox' name='passable[interests][]' value='movies'>
<input type='checkbox' name='passable[interests][]' value='art'>
<input type='checkbox' name='passable[interests][]' value='cars'>
<input type='checkbox' name='passable[interests][]' value='business'>
<input type='checkbox' name='passable[interests][]' value='comedy'>
<input type='checkbox' name='passable[interests][]' value='technology'>
</form>
Intermediate page:
<?php
function pass_previous_data ()
{
foreach ($_POST['passable'] as $name => $block)
foreach ($block as $value)
{
echo "<input type='hidden' name='passable[$name][]' value='$value'>";
}
}
?>
<form method="POST" ... >
// by default, form fields will not be forwarded
<input type='text' name='added_data' value='whatever'>
// inject previous data as hidden fields
<?php pass_previous_data (); ?>
// add more forwardable data
<input type='checkbox' name='passable[languages][]' value='English'>
<input type='checkbox' name='passable[languages][]' value='Español'>
<input type='checkbox' name='passable[languages][]' value='Deutsch'>
<input type='checkbox' name='passable[languages][]' value='Русский'>
</form>
The final page should see the whole packet of selected values as an array.
The system allows you to forward data across multiple pages by declaring input names as passable.
It makes retrieving data pretty straightforward with minimal PHP code.
All this being said, it's a pretty inefficient way of passing data around:
you generate a whole hidden HTML input to pass each single value.
You could encode your arrays with Json or PHP serialization mechanism instead, but I suppose you have your reasons to do otherwise.
Here is a one-page working demo of the above example (a little obfuscated by PHP/HTML blending though)
<!DOCTYPE html>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<?php
// recreate hidden fields to forward previous post data
function pass_previous_data ()
{
foreach ($_POST['passable'] as $name => $block)
foreach ($block as $value)
{
echo "<input type='hidden' name='passable[$name][]' value='$value'>";
}
}
if (!isset($_POST['page']))
{ // first page
?>
<body onload='document.getElementById("post").submit();'>
<form method="POST" id="post">
<input type='hidden' name='page' value='2'>
<input type='checkbox' name='passable[interests][]' value='movies' checked>
<input type='checkbox' name='passable[interests][]' value='art' checked>
<input type='checkbox' name='passable[interests][]' value='cars'>
<input type='checkbox' name='passable[interests][]' value='business'>
<input type='checkbox' name='passable[interests][]' value='comedy'>
<input type='checkbox' name='passable[interests][]' value='technology' checked>
</form>
</body>
<?php } else switch ($_POST['page']) {
case '2': // second page
?>
<body onload='document.getElementById("post").submit();'>
<form method="POST" id="post">
<input type='hidden' name='page' value='3'>
<?php pass_previous_data (); ?>
<input type='text' name='added_data' value='whatever'>
<input type='checkbox' name='passable[languages][]' value='English' checked>
<input type='checkbox' name='passable[languages][]' value='Español'>
<input type='checkbox' name='passable[languages][]' value='Deutsch' checked>
<input type='checkbox' name='passable[languages][]' value='Русский' checked>
</form>
</body>
<?php break;
case '3':
// final page
echo"<pre>";print_r ($_POST);echo"</pre>";
break;
}
?>

Checkbox Array only showing checked values - PHP

I have a form with many checkboxes.
ex.
...
<input name="dodatkowe[]" type="checkbox" value="1" />
<input name="dodatkowe[]" type="checkbox" value="1" />
<input name="dodatkowe[]" type="checkbox" value="1" />
...
I want to have all the checkboxes in the array. Array 'dodatkowe'.
When i checked all checkboxes have:
Array ( [0] => 1 [1] => 1 [2] => 1 )
but when i checked example only second I have:
Array ( [0] => 1 )
I need that, when i check example second checkbox:
Array ( [0] => 0 [1] => 1 [2] => 0)
give them indexes so you can reference them specifically...
...
<input name="dodatkowe[1]" type="checkbox" value="1" />
<input name="dodatkowe[2]" type="checkbox" value="1" />
<input name="dodatkowe[3]" type="checkbox" value="1" />
...
Not sure why you feel you need to see the unchecked values, this can be assumed to be the inverse of the checked values.... Any attempt to do this is a hack, and is unnecessary.
If a checkbox isn't checked it won't include it's value into the parameters but the first step would be to give the checkboxes a unique id:
<input name="dodatkowe[0]" type="checkbox" value="1" />
<input name="dodatkowe[1]" type="checkbox" value="1" />
<input name="dodatkowe[2]" type="checkbox" value="1" />
Then you can use PHP to check is the value is there:
$maxfields = 3;
$selectboxes = $_REQUEST['dodatkowe'];
for($i = 0; $i < $maxfields; $i++)
if(!isset($selectboxes[$i])) $selectboxes[$i] = 0;
This will set all non existent fields to 0 and $selectboxes should contain the result you are looking for.

Categories