Organizing the post array - php

Here is my form
<form name="input" action="http://localhost/shopper/index.php?route=module/cart/insert_shopper" method="post">
<input quantity="4" type="hidden" name="28" value="1">
<input type="hidden" quantity="3" name="29" value="1">
<input type="submit" value="Submit" />
I have this format
[post] => Array
(
[28] => 1
[29] => 1
)
I really want the post array to be products and then a list on product ids with quantities ...is there an easy way to change the form
so on the next page i can do this
$products = $_POST['products']
foreach( $products as $p)
{
if( isset($p) && $p<>'')
{
///// place your code here
}
}

<input type="hidden" name="products[29][3]" value="1">
$products = $_POST['products']
foreach( $products as $product_id=>$quantity)
{
echo $product_id;
echo $quantity;
}

In your HTML form you can add array brackets after the end of the name attribute value, eg:
<input type = 'hidden' name = 'products[]' value = '12'/>
<input type = 'hidden' name = 'qty12' value = '16'/>
<input type = 'hidden' name = 'products[]' value = '13'/>
<input type = 'hidden' name = 'qty13' value = '72'/>
<input type = 'hidden' name = 'products[]' value = '14'/>
<input type = 'hidden' name = 'qty14' value = '1'/>
The PHP in the receiving script will then treat $_POST['products'] as an array. The quantity can be seen by:
foreach($_POST['products'] as $k => $v) {
echo($_POST['qty'.$v] . "<br/>");
}

<form name="input" action="" method="post">
<input type="hidden" name="29" value="3">
<input type="hidden" name="28" value="4">
<input type="hidden" name="27" value="2">
<input type="submit" value="Submit"/>
<?php
if (!empty($_POST))
{
foreach ($_POST as $id => $quantity)
{
echo 'ID: '.$id.' quantity: '.$quantity;
}
}

<input type="hidden" name="28" value="4">
<input type="hidden" name="29" value="3">
Will give you
[post] => Array
(
[28] => 4
[29] => 3
)

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
)
)

How to deal with checkbox? [duplicate]

I have added a checkbox to a form that the user can dynamically add rows to. You can see the form here.
I use an array to pass the values for each row to a PHP email generator, and all works fine for other inputs, but I can't get the checkbox to work. The checkbox input currently looks like this:
<input type="checkbox" name="mailing[]" value="Yes">
Then in the PHP I have this:
$mailing = trim(stripslashes($_POST['mailing'][$i]));
But it is not working as expected, i.e. I am only seeing 'Yes' for the first checkbox checked, and nothing for subsequent checkboxes that are checked.
One further issue is that I would like the value 'No' to be generated for unchecked checkboxes.
Could someone help with this?
Thanks,
Nick
Form:
<form method="post" action="bookingenginetest.php">
<p>
<input type="checkbox" name="mailing[]" value="Yes">
<label>Full Name:</label> <input type="text" name="name[]">
<label>Email:</label> <input type="text" name="email[]">
<label>Telephone:</label> <input type="text" name="telephone[]">
<span class="remove">Remove</span>
</p>
<p>
<span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" />
</p>
</form>
Cloning script:
$(document).ready(function() {
$(".add").click(function() {
var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
x.find('input').each(function() { this.value = ''; });
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
});
$mailing = array();
foreach($_POST as $v){
$mailing[] = trim(stripslashes($v));
}
To handle unchecked boxes it would be better to set each checkbox with a unique value:
<input type="checkbox" name="mailing[1]" value="Yes">
<input type="checkbox" name="mailing[2]" value="Yes">
or
<input type="checkbox" name="mailing[a]" value="Yes">
<input type="checkbox" name="mailing[b]" value="Yes">
Then have a list of the checkboxes:
$boxes = array(1,2,3);
$mailing = array();
$p = array_key_exists('mailing',$_POST) ? $_POST['mailing'] : array();
foreach($boxes as $v){
if(array_key_exists($v,$p)){
$mailing[$v] = trim(stripslashes($p[$v]));
}else{
$mailing[$v] = 'No';
}
}
print_r($mailing);
You could also use this with a number of checkboxes instead:
$boxes = 3;
$mailing = array();
$p = array_key_exists('mailing',$_POST) ? $_POST['mailing'] : array();
for($v = 0; $v < $boxes; $v++){
if(array_key_exists($v,$p)){
$mailing[$v] = trim(stripslashes($p[$v]));
}else{
$mailing[$v] = 'No';
}
}
print_r($mailing);
Here's my solution:
With an array of checkboxes in the html like so...
<input type="hidden" name="something[]" value="off" />
<input type="checkbox" name="something[]" />
<input type="hidden" name="something[]" value="off" />
<input type="checkbox" name="something[]" />
<input type="hidden" name="something[]" value="off" />
<input type="checkbox" name="something[]" />
I then fix the posted array with this function...
$_POST[ 'something' ] = $this->fixArrayOfCheckboxes( $_POST[ 'something' ] );
function fixArrayOfCheckboxes( $checks ) {
$newChecks = array();
for( $i = 0; $i < count( $checks ); $i++ ) {
if( $checks[ $i ] == 'off' && $checks[ $i + 1 ] == 'on' ) {
$newChecks[] = 'on';
$i++;
}
else {
$newChecks[] = 'off';
}
}
return $newChecks;
}
This will give me an array with values of either 'on' or 'off' for each (and every) checkbox.
Note that the hidden input MUST be BEFORE the checkbox input in order for the function to work right.
Change the value for each checkbox to something unique:
<input type="checkbox" name="mailing[]" value="Yes-1">
<input type="checkbox" name="mailing[]" value="Yes-2">
etc. In order to do this from your jQuery code, add another line that assigns the value to the new checkbox:
x.find('input:checkbox').each(function() { this.value='Yes-'+n; });
You'll have to define n on the initial page load. Assuming you start with only one "person", just add right above your $(".add").click handler:
var n=1;
And then:
in your $(".add").click handler, increment the value of n
in your $(".remove").click handler, decrement the value of n
To get checked and unchecked both values in POST place a hidden field with exactly the same name but with opposite value as compared to the original chkbox value such that in this case the value will be '0'
<input type="hidden" name="chk_name[]" value="0" />
<input type="checkbox" name="chk_name[]" value="1"/>
<input type="hidden" name="chk_name[]" value="0" />
<input type="checkbox" name="chk_name[]" value="1"/>
<?php
function getAllChkboxValues($chk_name) {
$found = array(); //create a new array
foreach($chk_name as $key => $val) {
//echo "KEY::".$key."VALue::".$val."<br>";
if($val == '1') { //replace '1' with the value you want to search
$found[] = $key;
}
}
foreach($found as $kev_f => $val_f) {
unset($chk_name[$val_f-1]); //unset the index of un-necessary values in array
}
final_arr = array(); //create the final array
return $final_arr = array_values($chk_name); //sort the resulting array again
}
$chkox_arr = getAllChkboxValues($_POST['chk_name']); //Chkbox Values
echo"<pre>";
print_r($chkox_arr);
?>
Here's my solution:
<span>
<input class="chkBox" onchange="if($(this).is(':checked')){$(this).parent().find('.hidVal').prop('disabled',true);}else{$(this).parent().find('.hidVal').prop('disabled', false);}" type="checkbox" checked name="session[]" value="checked_value_here" />
<input type="hidden" class="hidVal" name="session[]" value="un_checked_value_here" />
</span>
<span>
<input class="chkBox" onchange="if($(this).is(':checked')){$(this).parent().find('.hidVal').prop('disabled',true);}else{$(this).parent().find('.hidVal').prop('disabled', false);}" type="checkbox" checked name="session[]" value="checked_value_here" />
<input type="hidden" class="hidVal" name="session[]" value="un_checked_value_here" />
</span>

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)

Identifying if no radio buttons selected with PHP

I'm trying to write some code that will determine if no radio buttons are selected on a form
the form consists of many fields but have just included the radio buttons in form below
<form action="myPHPPage.php" method="post">
Value 1 <input type="radio" name="basic" value="myValue1">
Value 2 <input type="radio" name="silver" value="myValue2">
Value 3 <input type="radio" name="gold" value="myValue3">
<input type="submit" name="send" value="Submit">
then in the myPHPPage.php page I have something like below to assign the POST value to a variable:
if(!isset($_POST['basic'])) {
$var = $_POST['basic'];};
$someValue = $var;
}
But I want some code like: If no radio buttons selected $var = $someValue
You need to bind all-radio buttons in a group like
Value 1 <input type="radio" name="basic" value="basic">
Value 2 <input type="radio" name="basic" value="silver">
Value 3 <input type="radio" name="basic" value="gold">
Then in PHP
<?php
if(isset($_POST['basic'])) { //remove ! from condition
$var = $_POST['basic'];};
echo $someValue = $var;
}
?>
TRY THIS....you should have all radio button same NAME
<form action="myPHPPage.php" method="post">
Value 1 <input type="radio" name="basic" value="myValue1">
Value 2 <input type="radio" name="basic" value="myValue2">
Value 3 <input type="radio" name="basic" value="myValue3">
<input type="submit" name="send" value="Submit">
</form>
here your php code on server after the submit is press
<?php
if(isset($_POST['send'])) { //change index to submit button name
if($_POST['basic'] == ''){ // if no button is selected then
$var = $someValue;
}//if ends here
else
{ //if any of the radio is selected "if you don't want else so remove that"
$var = $_POST['basic'];
}//else ends here
}//isset ends here
?>
Try this:
<?php
// Handle Post
if (isset($_POST['send']))
{
// Get Post Values
$basic = isset($_POST['basic']) ? $_POST['basic'] : '';
$silver = isset($_POST['silver']) ? $_POST['silver'] : '';
$gold = isset($_POST['gold']) ? $_POST['gold'] : '';
// Atleast one is selected
if (!empty($basic) || !empty($silver) || !empty($gold))
{
echo 'You have made atleast one selection';
}
else
{
echo 'You have not made any selection.';
}
}
?>
<form action="" method="post">
Value 1 <input type="radio" name="basic" value="myValue1">
Value 2 <input type="radio" name="silver" value="myValue2">
Value 3 <input type="radio" name="gold" value="myValue3">
<input type="submit" name="send" value="Submit">
</form>
If you are using radio, all the names of input radio for that particular option should be same.
Value 1 <input type="radio" name="basic" value="basic">
Value 2 <input type="radio" name="basic" value="silver">
Value 3 <input type="radio" name="basic" value="gold">
<?php
if(isset($_POST['basic']))
{
$var = $_POST['basic'];
}
?>
The first thing you have to know about radio button is that if they are reflecting the same attribute, they should have a same name.
Thus your form have to be changed like this.
<form action="myPHPPage.php" method="post">
Value 1 <input type="radio" name="radioName" value="basic">
Value 2 <input type="radio" name="radioName" value="silver">
Value 3 <input type="radio" name="radioName" value="gold">
<input type="submit" name="send" value="Submit">
Then you want to assign a value if no radio button is selected.
You can do the following:
$var="";
$someValue="abc";
if(isset($_POST['radionName'])) {
$var = $_POST['radionName'];// This means one radio button is selected, thus you have a value.
}
else{
$var=$someValue; // No radio button is selected, thus you can assign a default desired value.
}
<form action="myPHPPage.php" method="post">
if buttons are optional please make a group of radio button with name attribute value.
Value 1 <input type="radio" name="basic" value="myValue1">
Value 2 <input type="radio" name="basic" value="myValue2">
Value 3 <input type="radio" name="basic" value="myValue3">
<input type="submit" name="send" value="Submit">
Then use a php condition here.
<?php
if(isset($_POST['basic'])) {
$var = $_POST['basic'];};
$someValue = $var;
}
You can check all $_POST elements,than can compare name and their values.
foreach($_POST as $key=>$value)
{
echo "$key=$value";
}
PHP: Possible to automatically get all POSTed data?
<form action="myPHPPage.php" method="post">
Value 1 <input type="radio" name="basic" value="myValue1">
Value 2 <input type="radio" name="basic" value="myValue2">
Value 3 <input type="radio" name="basic" value="myValue3">
<input type="submit" name="send" value="Submit">
<?php
if(!isset($_POST['basic'])) {
$var = $_POST['basic'];};
$someValue = $var;
Please Try this one

Get each chekbox group values into separate variables upon form submission

I have multiple checkbox groups, and once the form is submitted, I want each group of checkboxes that were selected to be added to their own variable.
This is the form:
<form action="" method="get">
<p>apple <input type="checkbox" value="apple" name="fruits[]" /></p>
<p>orange <input type="checkbox" value="orange" name="fruits[]" /></p>
<p>peach <input type="checkbox" value="peach" name="fruits[]" /></p>
<br>
<p>red <input type="checkbox" value="red" name="colors[]" /></p>
<p>green <input type="checkbox" value="green" name="colors[]" /></p>
<p>blue <input type="checkbox" value="blue" name="colors[]" /></p>
<br>
<p>chicken <input type="checkbox" value="chicken" name="meats[]" /></p>
<p>pork <input type="checkbox" value="pork" name="meats[]" /></p>
<p>lamb <input type="checkbox" value="lamb" name="meats[]" /></p>
<button>submit</button>
</form>
And this is my code:
$string = 'fruits,colors,meats';
$str_array = explode(',', $string);
foreach ($str_array as $value) {
if (isset($_GET[$value])) {
$group_name = $_GET[$value];
foreach ($group_name as $group_item) {
$group_string .= ' ' . $group_item;
}
}
}
echo $group_string;
With that code, if I choose for example the first checkbox in each group and hit submit, I will get the following value of $group_string = apple red chicken in one string.
What I get does make sense to me as per the code I wrote, but what I want is for each option group to have its own variable to which its values are asigned, so what I want is to get is the following (assuming I again chose the first option from each group):
$fruits = 'apple';
$colors = 'red';
$meats = 'chicken';
But I don't know how to rewrite it so I get that. Also, the number of options groups is not known upfront, it has to happen dynamically.
Ok, I took the liberty of rewriting part of your php for my convenience but here it is
your new and improved php file
<?php
// assume we know beforehand what we are looking for
$groups = explode(',','fruits,colors,meats');
foreach ($groups as $group) {
if (isset($_GET[$group])) {
$vv = array();
foreach ($_GET[$group] as $item) $vv[] = $item;
$$group = implode(' ',$vv);
}
}
var_dump($fruits,$colors,$meats);
?>
I used a construct in PHP called variable variables. This is actually an almost identical answer as the one #Lohardt gave. I hope this can help you out. If it doesn't then post me a comment
You could do something like:
<input type="checkbox" value="apple" name="groups[fruits][]" />
<input type="checkbox" value="apple" name="groups[colors][]" />
<input type="checkbox" value="apple" name="groups[meats][]" />
Your $_POST will look like this:
Array
(
[groups] => Array
(
[fruits] => Array
(
[0] => apple
)
[colors] => Array
(
[0] => red
)
)
)
And it should be simple to use a foreach loop to get the keys and values.
Edit: then you can assign the value to variables like this:
${$key} = $value;
and use it you would do any variable:
echo $color;

Categories