So I am trying to email the results of a form using PHP. inside my form I have a bunch of checkboxes. The script below works when at least 1 checkbox in a group is checked. If none of the checkboxes are checked I receive the following error:
Warning: Implode() [function.implode]: Invalid augments passed in {name of php doc} on line {xxx} Array
Here is a sample of the code I'm using:
<?php
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
if(!$data[14]) //$data[14] is an array of checkbox values
{echo 'No User Selection';}
else
{echo implode(" | ", $data[14]);} //This is where the error occurs
?>
HTML code
<label for="b0" class="left">Item 1</label>
<input type="checkbox" name="b[0]" id="b0" value="Item 1"/>
<label for="b1" class="left">Item 2</label>
<input type="checkbox" name="b[1]" id="b1" value="Item 2"/>
<label for="b2" class="left">Item 3</label>
<input type="checkbox" name="b[2]" id="b2" value="Item 3"/>
ect....
Does anyone have an idea why I'm receiving this error?
Make sure the variable a) is set and b) is an array.
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
if ( !isset($data[14]) || !is_array($data[14]) ) {
echo 'No User Selection';
} else {
echo implode(" | ", $data[14]);
}
Always properly check variables using isset(), unless of course you like giant error logs! I also suggest using the $_POST keys as the keys for $data, thus making life even easier when you want to look up a specific $_POST item.
If the checkbox is not checked, it is not sent to the server.
I suggest you to do something like this:
<label for="b0" class="left">Item 1</label>
<input type="hidden" name="b[0]" value=""/>
<input type="checkbox" name="b[0]" id="b0" value="Item 1"/>
<label for="b1" class="left">Item 2</label>
<input type="hidden" name="b[1]" value=""/>
<input type="checkbox" name="b[1]" id="b1" value="Item 2"/>
<label for="b2" class="left">Item 3</label>
<input type="hidden" name="b[2]" value=""/>
<input type="checkbox" name="b[2]" id="b2" value="Item 3"/>
This way, you are sure that b[0], b[1], etc. are always sent
You are causing the problem yourself by making the data array. Just go straight to the POST array. Everything else is overcomplicating the problem.
<?php
if(!isset ($_POST['b']) || !is_array($_POST['b'])) {
echo 'No User Selection';
} else {
echo implode(" | ", $_POST['b']);
}
?>
In addition, if the content of your form changes slightly, or you want to reorder the fields then your magic number 14 will no longer work.
Your code will be unbelievably fragile unless you change it.
Related
I have multiple checkboxes with names of adminMeta[], such as:
<input type="checkbox" name="adminMeta[name1]" value="1" />
<input type="checkbox" name="adminMeta[name2]" value="1" />
and so on and I also have text inputs like this too with the same names.
When the data is posted, I am looping through using a foreach loop:
foreach($_POST["adminMeta"] as $a => $b) {
}
inside the loop, I add/update the record in my database depending on whether it exists already or not.
But I am having some issues with checkboxes and knowing whether they are checked or not.
I have tried using if(isset($b)) but that hasn't worked.
How can I tell inside my loop, whether a checkbox is checked or not?
If a checkbox is not checked, then it is not a successful control.
If it is not a successful control, then it won't be included in the form data at all.
If it isn't in the form data, then it won't appear when you loop over the form data.
So
If it is in the form data, then it is checked
Otherwise it is not checked
Normally I'd approach this problem with something along the lines of:
$list_of_checkboxes = [ "name1", "name2" ];
Then generate the form with:
foreach ($list_of_checkboxes as $name) {
?>
<label>
<input type="checkbox"
name="adminMeta[]"
value="<?php echo htmlspecialchars($name); ?>">
<?php echo htmlspecialchars($name); ?>
</label>
<?php
}
Then test the data with:
foreach ($list_of_checkboxes as $name) {
if (in_array($name, $_POST['adminMeta'])) {
# Checked
} else {
# Not checked
}
}
Another approach would be to set hidden inputs before each check with default value of 0:
<input type="hidden" name="adminMeta[name1]" value="0" />
<input type="checkbox" name="adminMeta[name1]" value="1" />
<input type="hidden" name="adminMeta[name2]" value="0" />
<input type="checkbox" name="adminMeta[name2]" value="1" />
Now you will receive the data even if you don't check the checkboxes.
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;
I have this code on my form for the checkboxs:
<input type="hidden" name="option_desc[]" value="option 1"/>
<label><input type="checkbox" name="option_price[]" value="10" class="option_checkbox"/>option 1</label>
<input type="hidden" name="option_desc[]" value="option 2"/>
<label><input type="checkbox" name="option_price[]" value="20" class="option_checkbox"/>option 2</label>
<input type="hidden" name="option_desc[]" value="option 3"/>
<label><input type="checkbox" name="option_price[]" value="30" class="option_checkbox"/>option 3</label>
I'm trying to get the POST values of the checkbox that the user checked (for example, if he checked the second checkbox: "option 2" + "20") and store them:
$articleDetails['options'] = array();
$count = 0;
if(is_array($_POST['option_price'])){
foreach($_POST['option_price'] as $key => $value){
if($value){
$articleDetails['options'][$count]['option_price'] = $_POST['option_price'][$key];
$articleDetails['options'][$count]['option_desc'] = $_POST['option_desc'][$key];
$count++;
}
}
}
When the user check one of the checkbox, the appropriate 'option_price' is stored correctly, but the 'option_desc' is not the one that belongs to the CHECKED checkbox (for example: when the second checkbox is checked the values that I get are "20" (GOOD) and "option 1" (NOT GOOD).
What I'm doing wrong?
Thanks.
The problem you are having is that if checkboxes are not checked, the data won't get POSTed while your hidden inputs will always be posted. Frankly, I don't see what value your hidden inputs give you here. They tell you absolutely nothing about the posted data that you don't already know about on the server.
You should simply use a defined index in your array notation for the checkbox field, like this:
<input type="checkbox" name="option_price[1]" value="10" class="option_checkbox"/>option 1</label>
<input type="checkbox" name="option_price[2]" value="20" class="option_checkbox"/>option 2</label>
<input type="checkbox" name="option_price[3]" value="30" class="option_checkbox"/>option 3</label>
Note: I didn't use zero-indexed array here as I figured you might want to directly relate $_POST['option_price'][1] to "option 1".
To add some examples related to the discussion in comments below. Say for example you had some option_price checkboxes you want to output, and they come from some dynamic source. Your code to to generate the checkboxes might look something like this:
$price_options = array(
array(
'description' => 'eBook',
'value' => 10
),
array(
'description' => 'articles',
'value' => 20
),
// and so on
);
$count = count($price_options)
for($i = 1; $i<= $count; $i++) {
?>
<input type="checkbox" name="option_price[<?php echo $i; ?>]" value="<?php echo $price_options[$i]['value']; ?>" class="option_checkbox"/><?php echo $price_options[$i]['description']; ?></label>
<?php
} // end for
When POSTing you know that every $_POST['option_price'][x] would correspond to the item at $price_options[x].
You could simply iterate of $_POST['option_price'] to see which items are selected like this:
if(!empty($_POST['option_price']) {
foreach ($_POST['option_price'] as $index => $value) {
// verify value hasn't been tampered with
if ((int) $value === $price_options[$index]['value']) {
// set description
$description = $price_options[$index]['description'];
var_dump($description, $value);
}
}
}
I would suggest give names to input like
<input type=hidden name="option[1][desc]"/>
<input type=hidden name="option[1][price]"/>
Then I think it would be easy to run a forreach as well.
I have this simple form:
HTML:
<input type="checkbox" name="product[]" value="20$" /> book
<input type="checkbox" name="product[]" value="30$" /> plane
PHP:
$product = $_POST['product'];
foreach($product as $value) {
echo $value;
}
Note:
The user can choose one or two ... products.
Question:
I want to know if there is a solution to get the name too, like adding an ID class or something ..
Basically I cant get the name attribute because I didn't sent it with the form.
Add the missing information to your POST-parameters:
<input type="checkbox" name="product[book]" value="20$" /> book
<input type="checkbox" name="product[plane]" value="30$" /> plane
You can iterate over it like this:
foreach ($_POST['product'] as $name => $value) {
// ...
}
You can use the option presented by elusive, but it seems that in this case you're passing the price from the client to the server. That might allow people to fraud. They could with only a little hacking send another (lower) price. If you just send 'book' and redetermine the price on the server, this won't be a problem.
If you choose that path, you can just put the product ('book') in the value:
<input type="checkbox" id="book" name="product[]" value="book" />
<label for="book">book</label>
<input type="checkbox" id="plane" name="product[]" value="plane" />
<label for="plane">plane</label>
I just want to have php determines whether a checkbox is checked, but I am running into a problem of getting the right return. Help please.
My html code
<label>
<input name="Language" type="checkbox" id="aa" checked="checked" />
One</label>
<label>
<input name="Language" type="checkbox" id="bb" />Two</label>
<label>
<input type="checkbox" name="Language" id="cc" />Three</label>
I pass the values to php by the $_GET method
my php code:
$aa=$_GET["aa"];
$bb=$_GET["bb"];
$cc=$_GET["cc"];
echo $aa."<br>";
echo $bb."<br>";
echo $cc."<br>";
the output is
true
false
false
I next want to just determine if each box is checked and if so, do something.
if ($aa == true) { $abc="checked";}
else { $abc="not checked"; }
if ($bb == true) { $cde="checked";}
else { $cde="not checked"; }
if ($fgh == true) { $fgh="checked";}
else { $fgh="not checked"; }
But the if statements always return true, even if the box is not checked. I tried variations of "===" and "!=", but it does not seem to work.
TIA
if (isset($_GET['checkbox_name'])) { ... }
Form controls (with the exception of file inputs, and with some special rules for image inputs) always submit strings. There is no concept of a boolean in a query string or a form encoded POST body.
The id is irrelevant — only the name and value matter (at least as far as PHP is concerned).
Since you haven't given them values they will, IIRC, default to on so if you are doing a comparison you should look for that. Looking with isset is simpler though. This is somewhat beside the point though, since your example gives them all the same name and value, so you can't differentiate between them.
Additionally, due to an oddity of the PHP form data parser, you have to end the with [] if you want multiple elements with the same name.
You probably want to do something like this:
<label>
<input name="Language[]" type="checkbox" id="aa" checked="checked" value="One" />
One</label>
<label>
<input name="Language[]" type="checkbox" id="bb" value="Two" />Two</label>
<label>
<input type="checkbox" name="Language[]" id="cc" value="Three" />Three</label>
Important: Note the addition of values and the change in name.
Then in PHP $_GET['Language'] will be an Array of the values of the checked checkboxes, which you can loop over.
Try isset()
I think your HTML code should be like
<label>
<input name="Language[]" type="checkbox" id="aa" checked="checked" value ="1" />One
</label>
<label>
<input name="Language[]" type="checkbox" id="bb" value ="2" />Two
</label>
<label>
<input name="Language[]" type="checkbox" id="cc" value ="3" />Three
</label>
and then by using something like
$count = count($_GET["Language"]); you can count the number of checkboxes checked.
Or do
$arr = $_GET["Language"]; //$arr is an array that contains the values of the checked checkboxes
Then you can foreach over the array
foreach( $arr as $item)
{
echo $item . "</br>"; /* Will print 1,2 and 3 (mind newlines)*/
}
In my PHP I got it from $_POST['checkbox_name'], and I found that the variable had the value on when the box was checked (i.e. it existed even if the checkbox was clear).