Validate checkboxes sent in array - php

I have a form with multiple checkboxes, which I want to put into an array. I go by the example provided here: http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
So I've prepared the files:
checkboxes.php:
<form action="checkboxes2.php" method="post">
<input type="checkbox" name="tags[]" value="1" />1<br>
<input type="checkbox" name="tags[]" value="2" />2<br>
<input type="checkbox" name="tags[]" value="3" />3<br>
<input type="checkbox" name="tags[]" value="4" />4<br>
<input type="submit" value="Send" />
</form>
checkboxes2.php:
<?php
print_r($_POST["tags"]);
?>
Pretty simple...I realize I should only get the value of these textboxes and not if they have been selected or not. But I still get this error:
Undefined index: tags in checkboxes2.php on line 2
I have absolutely no idea what I did wrong here. I went by the example in the link above and did everything exactly the same (mainly copy/pasting and changing some parts like adding a submit button) but I don't get the output as shown in the example. I should at least get the values of each of these checkboxes, right?
What I want to do: I want to check the array of checkboxes, see which ones have been selected and add "yes" or "no" into a second array, like this:
<?php
$number1 = $_POST["tags"];
$number2 = array();
foreach($number1 as $number1_output)
{
if(isset($number1_output))
{
$number2[] = "yes";
}
else
{
$number2[] = "no";
}
}
print_r($number2);
?>
Well...it only half works. Only the checkboxes that have been selected are added to the array. So if I select "3" and "4" I get this:
Array ( [0] => yes [1] => yes )
What is the best way to deal with checkboxes in arrays and validating them?

Checkboxes which are not selected to do not send anything when the form submits. That means if NONE of those tags checkboxes are selected, there will be no tags attribute in the $_POST array.
As such, your code should be
<?
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['tags'])) {
print_r($_POST['tags']);
}
}
?>
The first line verifies that a POST has actually taken place, and the second line verifies that there's actually any data to dump out.
For the rest of your code, the isset is rather pointless... Since a checkbox is only present in the POST data if it was selected, there's no point in doing the isset() within your foreach loop - there'd be nothing to foreach on if there were no checkboxes, so by definition everything in the foreach will be isset() == true anyways.
As such, your foreach loop will only produce yes values, never a no.
A better workaround is to specify array keys within your form:
<input type="checkbox" name="tags[1]" value="1" />
<input type="checkbox" name="tags[2]" value="2" />
etc...
then have
<?php
if (b blah blah blah verify post stuff) {
for ($i = 1; $i <= $max_tags_allowed; $i++) {
if (isset($_POST['tags'][$i])) {
$message2[] = 'yes';
} else {
$message2[] = 'no';
}
}
}

Alternatively, if you want to have checkboxes that also send a value if they are not checked, you can add a Hidden input field before the checkbox:
<input type="hidden" name="tag[1]" value="off" />
<input type="checkbox" name="tag[1]" value="on />
Because the checkbox is only sent if it is set, but it overrides the hidden as it is later in the HTML, you will now always have tag[1] set with either 'off' or 'on' depending on whether or not the box was checked.

First create an array that holds "no" with all the possible keys, like this:
$no = array(0 => "no", 1 => "no"); // or array("no", "no");
Then you can get your desired array like that:
$checkValues = array_flip($_POST["tags"]) + $no;
This way the values in $_POST["tags"] will become keys, and the + operator merges the two array keeping the keys, also omitting values from the second array, if they are present in the first array. This way you can just check like this:
$fourthChecked = $checkValues[4] !== "no";
I thought its much simpler than the other answers. Good luck!

In your checkboxes.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>My form</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" languaje="javascript">
$(document).ready(function() {
$('.checkbox').click(function(){
var values="";
$('.checkbox:checked').each(function(index) {
values+=$(this).val();
$('#tagsVal').val(values);
});
});
});
</script>
</head>
<body>
<form action="checkboxes2.php" method="post">
<input type="checkbox" name="tags1" value="1" class="checkbox"/>1<br><!--Notice the class="checkbox" attribute is important for the jquery function-->
<input type="checkbox" name="tags2" value="2" class="checkbox"/>2<br>
<input type="checkbox" name="tags3" value="3" class="checkbox"/>3<br>
<input type="checkbox" name="tags4" value="4" class="checkbox"/>4<br>
<input type="hidden" name="tagsVal" id="tagsVal" value="" />
<input type="submit" value="Send" />
</form>
</body>
</html>
So what you'll get in your $_POST['tagVal'] you'll get your values. If checkbox 1,3 and 4 are checked you'll get a string 134.
In your checkboxes2.php you'll only have to split the string into array if you need it.
$arr1 = str_split($_POST['tagVal']);
Regards
Luis

Related

How to write a conditional statement with a value but only if it's the only value?

if($uriarray['value'] == 0 ){
I have an input form which includes values. The values are in a checkbox. I want to show something if it's the only value, but not if it's included with other values. So if the value is 0 I want to show something but if it includes other values like 1,2,3 etc, I don't want to show it. Is this something that's possible?
If & only if?
It depends on your HTML form. For example, if you specify the names of the checkboxes in array-form like:
<input type="checkbox" name="uriarray[]" value="0" />
<input type="checkbox" name="uriarray[]" value="1" />
<input type="checkbox" name="uriarray[]" value="2" />
<input type="checkbox" name="uriarray[]" value="3" />
you would receive an array in PHP with all checked values.
<?
if (count($_POST['uriarray']) == 1) {
$onlyValues = $_POST['uriarray'][0];
}
?>
If you also want to check the single value to be 0:
<?
if ((count($_POST['uriarray']) == 1) && ($_POST['uriarray'][0] == "0")) {
//Do something
}
?>

checkboxes in php form doesn't work

How can I use the conditional OR in a form with isset?
I have this but it does not work.
FORM HTML:
...
<input type="checkbox" name="carga1">
<input type="checkbox" name="carga2">
...
and the PHP
$cargas=array($_POST['carga1'],$_POST['carga2'],$_POST['carga3'],
$_POST['carga4'],$_POST['carga5'],$_POST['carga6'],
$_POST['carga7'],$_POST['carga8'],$_POST['carga9'],
$_POST['carga10'],$_POST['carga11'],$_POST['carga12'],
$_POST['carga13'],$_POST['carga14'],$_POST['carga15'],
$_POST['carga16'],$_POST['carga17'],$_POST['carga18']);
if(isset($cargas[0]) ││ isset ($cargas[1])){
$cargas[0]=5.62;
$cargas[1]=4.5;
echo "$cargas[0]<br>";
echo "$cargas[1]<br>";
}
i expect that this works but is not.
Only checked checkbox is posted to the server.You have to change your condition using pregmatch and work accordingly.
$postData = $_POST;
foreach ($postData as $key => $value) {
$match = preg_match('|cargas(\d+)|', $key, $matches);
if ($match) {
$index = $matches[1];
if($index == 0 || $index == 1){
// do your stuff which you would have done in case of $cargas[0] ,$cargas[1]
}
}
}
I think array is not Suitable way to do this try following
try this
<input type="checkbox" name="carga1">
<input type="checkbox" name="carga2">
.....................................
<input type="submit" name="submit">
<?php
if(isset($_POST['submit'])){
//
$category1=$_POST['carga1'];
$category2=$_POST['carga2'];
$category3=$_POST['carga3'];
if(isset($category1) ││ isset ($category2)){
$category1=5.62;
$category2=4.5;
echo "$category1<br>";
echo "$category2<br>";
}
}
?>
only the checked checkboxes get posted. so it needs slightly different appraoch.
You can acheive it like this-
put a hidden input with the same name as the checkbox that might not be checked. I think it works so that if the checkbox isn't checked, the hidden input is still successful and sent to the server but if the checkbox is checked it will override the hidden input before it. This way you don't have to keep track of which values in the posted data were expected to come from checkboxes.
<form>
<input type='hidden' id='testName' value='0' name='carga1'>
<input type='checkbox' id='testNameHidden' value='1' name='carga1'>
</form>
Before submitting the form , disabled the hidden field based on the checked condition.
<script>
if(document.getElementById("testName").checked){
document.getElementById('testNameHidden').disabled = true;
}
</script>
I personally think its the easiest approach for this.
ok, check boxes in html works as follows,
<input type="checkbox" name="carga1" value="1">
<input type="checkbox" name="carga2" value="123">
in php,
if the check box is in checked state during the submission, you will get
isset($_POST['carga1']) as true, else the form element would not be available in post data, hence false.
and in cheked state you will get value for
$_POST['carga1'] as 1 and
$_POST['carga2'] as 123
and if you want to group the check boxes in form you can use a single name for multiple check boxes and different values,
<input type="checkbox" name="carga[]" value="1">
<input type="checkbox" name="carga[]" value="2">
<input type="checkbox" name="carga[]" value="3">
<input type="checkbox" name="carga[]" value="4">
and in php you will get an array of selected values of the check boxes
$arr=$_POST['carga'];
and you can use foreach to iterate through the values,,,

how to get value of checked with checkbox row in php?

I am trying to get values of rows which are checked using checkbox. So when I submit the form I want values of selected rows but I am not able to figure it out how to get it. Can anybody help me or guide me?
<?php
if(isset($_POST['invite'])){
// what should I write here to get value of hidden fields name and email which was selected
}
?>
<!doctype>
<html><head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
// performing select all /deselect all checkbox operation
<SCRIPT language="javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
</head><body>
<div class = 'middle' style = 'width : 700px;background-color:beige'>
// creating grid view
<form type="post" name ="contacts">
<span><input type="checkbox" id="selectall"/></span>
<div class = 'middle row'>NAME</div>
<div class = 'middle row'>E-MAIL</div>
<div class='line'></div>
<div class='line'></div>
<?php foreach($email as $e){
echo "<div>
<span><input type='checkbox' class='case' name='case'/></span>
<div class='row'>".$e['name']."
<input name='cname[]' type='hidden' value =".$e['name']."></div>
<div class='row'>".$e['email']."
<input name='cemail[]' type='hidden' value =".$e['email']."></div>
</div><div class='line'></div>";
}
echo"<input type='submit' name='invite' value='invite'>
</form></div></body></html>";
}?>
After submitting the form, the value of a checked checkbox appears in the $_POST array like any other form fields. In your case, you have multiple checkboxes named case. None of those has a specific value assigned, so $_POST['case'] will equal on if any checkbox is checked, so this won't help you at all.
Change the name of the checkbox to case[] and assign a unique value to each, and $_POST['case'] will contain an array of the values of all checked checkboxes after submit. For instance, you could repeat the values of the hidden fields in the value attribute of your checkbox.
I wrote a small php script that should help you to understand, how checkboxes work with php. Just run it, play with the checkboxes and have a look at the $_POST array afterwards.
<!doctype html>
<html>
<body>
<form method="post">
<input type="checkbox" name="test[]" value="0"/>
<input type="checkbox" name="test[]" value="1"/>
<input type="checkbox" name="test[]" value="2"/>
<input type="checkbox" name="test[]" value="3"/>
<input type="checkbox" name="test[]" value="4"/>
<input type="submit"/>
</form>
<pre><?php var_dump($_POST); ?></pre>
</body>
</html>
If you want to keep your hidden fields and don't want to repeat their values in the checkbox element, you can also use the array key of their arrays as checkbox value:
<?php
$i = 0;
foreach($email as $e) {
echo "<div>
<span><input type='checkbox' class='case' name='case[]' value='".$i."'/></span>
<div class='row'>".$e['name']."
<input name='cname['".$i."']' type='hidden' value =".$e['name']."></div>
<div class='row'>".$e['email']."
<input name='cemail['".$i."']' type='hidden' value =".$e['email']."></div>
</div><div class='line'></div>";
$i++;
}
Now, if $_POST['case']contains the values 2, 4 and 8 for instance, the emails you are looking for, are in $_POST['cemail'][2], $_POST['cemail'][4] and $_POST['cemail'][8]. Same applies for $_POST['cname'], of course.
First of all, there's a mistake in an argument of form tag:
<form type="post"
This should read
<form method="post"
Then, since you store name and e-mail in the inputs named cname[] and cemail[], they will be passed respectively in $_POST['cname'] and $_POST['cemail'] variables. Note that you named them in a way they will be passed as arrays, so actually, $_POST['cname'] is an array - it contains a key-value pair of 0 and the value attribute of the input control. So actually, your name and e-mail will be in $_POST['cname'][0] and $_POST['cemail'][0] variables.
Please analyse and also read Dealing with Forms section of PHP manual.

POSTing Checkboxes with Submit button to MySQL database

Currently, I have a piece of code which displays four checkboxes and allows a user to select the checkboxes, click submit, and the data, through the POST method, will be sent to the database (called "Spreadsheet") where it would be stored.
Typically, with a radio button, the data stored is only one element. But I noticed that with checkboxes, the elements (for my case specifically) could range from zero to four items. So my issue with my code is, only one element gets stored, even if I press all four. I think I have to store the items as an array, but how do I store + retrieve said items to and from the database?
Below is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html> <!-- tells browser this is an HTML document -->
<head> <!-- container of all head elements --> </head>
<body> <!-- Begin the content of the document -->
<?
if (isset($_POST['formSubmit2'])){
$category = $_POST['category'];
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
while($row = mysql_fetch_array($query)){
$values = array('0 - Luxury','1 - Brand','2 - Retailer','3 - B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category" value="<?php echo $values[$i]; ?>" id="rbl_0" <? if($row['category'] == $i) echo "checked='checked'"; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
</body>
</html>
Instead of passing in name="category", set it to "$category[]".
You should be able to retrieve it from $_POST, set it to a new variable, and manipulate it how you want.
if (isset($_POST['formSubmit2'])){
$submitted_category = $_POST['$category'];
$accountID = $_POST['accountID'];
// rest of your code...
}
Hope that helped.
You have to give each checkbox a different name because you are overwriting their values if not.
You can also give them an array name like category[] resulting in something like this:
<input type="checkbox" name="category[]" value="value 1"/> value 1<br/>
<input type="checkbox" name="category[]" value="value 2"/> value 2<br/>
<input type="checkbox" name="category[]" value="value 3"/> value 3<br/>
And then retrieve them with:
$categories = $_GET['category'];
foreach($categories as $category){
echo "Selected " . $category . "<br/>";
}
See as well: How do I create arrays in a HTML ?Docs
You can serialize your array and then store it in a varchar column in your DB
Save:
$values = array(...);
$data = serialize($values);
// Store data in your database
Retrieve:
// $data should come from your DB
$values = unserialize($data);
// Now values holds your array
For sending multiple values in HTTP POST request upon form submission you need to define HTML array.
Please refer the below code snippet
<input type="checkbox" name="category[]" value="0"/>Luxury
<input type="checkbox" name="category[]" value="1"/> Brand
<input type="checkbox" name="category[]" value="2"/> Retailer
<input type="checkbox" name="category[]" value="3"/> B2B
POST values for checkbox will be accessible through superglobal variable $_POST['category']
Here S_POST['category'] will be accessible as an array.
e.g $_POST['category'][0],
$_POST['category'][1],
$_POST['category'][2],
$_POST['category'][3]
So you need to iterate through an array for insertion of individual values for checkbox.

Submit an HTML form with empty checkboxes

I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.
However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.
How can I get around this? Thanks.
I've used this technique from time to time:
<input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />
note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.
if (isset($_POST['checkbox'])) {
// checkbox has been checked
}
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:
if (empty($_POST['myCheckbox']))
....
else
....
In PHP empty() and isset() don't generate notices.
Here is a simple workaround using javascript:
before the form containing checkboxes is submitted, set the "off" ones to 0 and check them to make sure they submit. this works for checkbox arrays for example.
///// example //////
given a form with id="formId"
<form id="formId" onSubmit="return formSubmit('formId');" method="POST" action="yourAction.php">
<!-- your checkboxes here . for example: -->
<input type="checkbox" name="cb[]" value="1" >R
<input type="checkbox" name="cb[]" value="1" >G
<input type="checkbox" name="cb[]" value="1" >B
</form>
<?php
if($_POST['cb'][$i] == 0) {
// empty
} elseif ($_POST['cb'][$i] == 1) {
// checked
} else {
// ????
}
?>
<script>
function formSubmit(formId){
var theForm = document.getElementById(formId); // get the form
var cb = theForm.getElementsByTagName('input'); // get the inputs
for(var i=0;i<cb.length;i++){
if(cb[i].type=='checkbox' && !cb[i].checked) // if this is an unchecked checkbox
{
cb[i].value = 0; // set the value to "off"
cb[i].checked = true; // make sure it submits
}
}
return true;
}
</script>
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name
<FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
<input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
<input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
<input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
<input type="checkbox" name="option[]" value="Option1">Option1<br/>
<input type="checkbox" name="option[]" value="Option2">Option2<br/>
<input type="checkbox" name="option[]" value="Option3">Option3<br/>
<input type="submit" value="Ver">
Use this
$myvalue = (isset($_POST['checkbox']) ? $_POST['checkbox'] : 0;
Or substituting whatever your no value is for the 0
We are trouble on detecting which one checked or not.
If you are populating form in a for loop, please use value property as a data holder:
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i ?>"
<?endfor;?>
If submit form you'll get order numbers of checkboxes that checked (in this case I checked 3rd and 4th checkboxes):
array(1) {
["active"]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
When you are processing form data in loop, let's say in post.php, use following code to detect if related row is selected:
if(in_array($_POST['active'] ,$i))
$answer_result = true;
else
$answer_result = false;
Final code for testing:
<?php if (isset($_POST) && !empty($_POST)):
echo '<pre>';
var_dump($_POST);
echo '</pre>';
endif;
?>
<form action="test.php" method="post">
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i; ?>" />
<?php endfor;?>
<button type="submit">Submit</button>
</form>
Although many answers were submitted, I had to improvise for my own solution because I used the customized check-boxes. In other words, none of the answers worked for me.
What I wanted to get is an array of check-boxes, with on and off values. The trick was to submit for each check-box on/off value a separator. Lets say that the separator is ";" so the string you get is
;, on, ;, ;, ;
Then, once you get your post, simply split the data into array using the "," as a character for splitting, and then if the array element contains "on", the check-box is on, otherwise, it is off.
For each check-box, change the ID, everything else is the same... and syntax that repeats is:
<div>
<input type="hidden" name="onoffswitch" class="onoffswitch-checkbox" value=";" />
...some other custom code here...
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch1" checked>
</div>
EDIT: instead of the ";", you can use some KEY string value, and that way you will know that you did not mess up the order, once the POST is obtained on the server-side... that way you can easily create a Map, Hash, or whatever. PS: keep them both within the same div tag.

Categories