How to validate a checkbox input using PHP? - php

I have two check boxes in my form:
<div class="label-input-wrapper pickup">
<div class="form-label">I need Airport pick-up</div>
<div class="form-input">
<input type="checkbox" name="pick_up" value="Yes" />Yes
<input type="checkbox" name="pick_up" value="No" />No
<div class="error-msg">
<?php if(isset($errors['pick_up_no'])) { echo '<span style="color: red">'.$errors['pick_up_no'].'</span>'; } ?>
</div>
</div>
</div>
Variable that saves the value of the above check boxes: $pickup = $_POST['pick_up'];
Validation:
//Check the airport pickup and make sure that it isn't a blank/empty string.
if ($pickup == ""){
//Blank string, add error to $errors array.
$errors['pick_up_no'] = "Please let us know your airport pick up requirement!";
}
if (($pick_up = Yes) && ($pick_up = No)) {
//if both selected, add error to $errors array.
$errors['pick_up_no'] = "Can not select Yes and No together!";
}
But the above validation just printing Can not select Yes and No together! if both are NOT selected, or if only one selected or even both are selected. It gives same error message for all the selections. Why?

You're presently assigning with a single = sign instead of comparing == with
if (($pick_up = Yes) && ($pick_up = No))
you need to change it to
if (($pick_up == "Yes") && ($pick_up == "No")){...}
while wrapping Yes and No inside quotes in order to be treated as a string.
Edit:
Your best bet is to use radio buttons, IMHO.
Using checkboxes while giving the user both Yes and No options shouldn't be used; it's confusing.
It should either be Yes OR No and not and.
<input type="radio" name="pick_up" value="Yes" />Yes
<input type="radio" name="pick_up" value="No" />No
That is the most feasible solution.

I don't know why you need a checkbox for this (this is what radio button's are supposed to do), but you can do it something like:
if(!isset($_POST['pick_up']) || count($_POST['pick_up']) > 1) {
echo 'please select at least 1 choice';
} else {
echo $_POST['pick_up'][0];
}
Then make your checkbox names:
name="pick_up[]"
Or if you really need to have separate error messages. Do something like this:
$errors['pick_up_no'] = '';
if(!isset($_POST['pick_up'])) {
$errors['pick_up_no'] = "Please let us know your airport pick up requirement!";
} elseif(count($_POST['pick_up']) > 1) {
$errors['pick_up_no'] = "Can not select Yes and No together!"; // weird UX, should have prevented this with a radio button
}
if($errors['pick_up_no'] != '') {
echo $errors['pick_up_no'];
} else {
echo $_POST['pick_up'][0];
}

It is impossible for $_POST['pick_up'] to be both yes and no at the same time since the name is pick_up and not pick_up[] <- pointing to multiple variables. So it will either be yes or no either way because one parameter will overwrite the other. You would have to use javascript to verify only one is checked before submit in that case.

Use array of checkbox field elements;
<input type="checkbox" name="pick_up[]" />Yes
<input type="checkbox" name="pick_up[]" />No
then in your PHP script:
<?php
$pick_ups=$_POST['pick_up'];
$first=isset($pick_ups[0]); //true/false of first checkbox status
$second=isset($pick_ups[1]); //true/false of second checkbox status
?>
Again, as you've already been told, you should use radio-buttons for this purpose! Take into account that $_POST does not send checkbox if it is not set (check with isset($_POST['name'])

Related

How to get checkbox value if it is not checked? [duplicate]

How to read if a checkbox is checked in PHP?
If your HTML page looks like this:
<input type="checkbox" name="test" value="value1">
After submitting the form you can check it with:
isset($_POST['test'])
or
if ($_POST['test'] == 'value1') ...
Zend Framework use a nice hack on checkboxes, which you can also do yourself:
Every checkbox generated is associated with a hidden field of the same name, placed just before the checkbox, and with a value of "0". Then if your checkbox as the value "1", you'll always get the '0' or '1' value in the resulting GET or POST
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">
When using checkboxes as an array:
<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">
You should use in_array():
if(in_array('Orange', $_POST['food'])){
echo 'Orange was checked!';
}
Remember to check the array is set first, such as:
if(isset($_POST['food']) && in_array(...
Let your html for your checkbox will be like
<input type="checkbox" name="check1">
Then after submitting your form you need to check like
if (isset($_POST['check1'])) {
// Checkbox is selected
} else {
// Alternate code
}
Assuming that check1 should be your checkbox name.And if your form submitting method is GET then you need to check with $_GET variables like
if (isset($_GET['check1'])) {
// Checkbox is selected
}
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.
HTML Code: (for Add Page)
<input name="status" type="checkbox" value="1" checked>
Hint: remove checked if you want to show it as unchecked by default
HTML Code: (for Edit Page)
<input name="status" type="checkbox" value="1"
<?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>
PHP Code: (use for Add/Edit pages)
$status = $_POST['status'];
if ($status == 1) {
$status = 1;
} else {
$status = 0;
}
Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.
To check if a checkbox is checked use empty()
When the form is submitted, the checkbox will ALWAYS be set, because ALL POST variables will be sent with the form.
Check if checkbox is checked with empty as followed:
//Check if checkbox is checked
if(!empty($_POST['checkbox'])){
#Checkbox selected code
} else {
#Checkbox not selected code
}
You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.
i.e.: With a POST form using a name of "test" (i.e.: <input type="checkbox" name="test"> , you'd use:
if(isset($_POST['test']) {
// The checkbox was enabled...
}
You can do it with the short if:
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
or with the new PHP7 Null coalescing operator
$check_value = $_POST['my_checkbox_name'] ?? 0;
Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set
Example:
if(isset($_POST["testvariabel"]))
{
echo "testvariabel has been set!";
}
Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:
//EMPTY ALL VALUES TO 0
$queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
if(!empty($_POST['check_menus'])) {
foreach($_POST['check_menus'] as $checkU) {
try {
//UPDATE only the values checked
$queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
} catch(PDOException $e) {
$msg = 'Error: ' . $e->getMessage();}
}
}
<input type="checkbox" value="menu_news" name="check_menus[]" />
<input type="checkbox" value="menu_gallery" name="check_menus[]" />
....
The secret is just update all VALUES first (in this case to 0), and since the will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.
Example is PHP but applies for everything.
Have fun :)
$is_checked = isset($_POST['your_checkbox_name']) &&
$_POST['your_checkbox_name'] == 'on';
Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.
A minimalistic boolean check with switch position retaining
<?php
$checked = ($_POST['foo'] == ' checked');
?>
<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>
<?php
if (isset($_POST['add'])) {
$nama = $_POST['name'];
$subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";
echo "Name: {$nama} <br />";
echo "Subscribe: {$subscribe}";
echo "<hr />";
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >
<input type="text" name="name" /> <br />
<input type="checkbox" name="subscribe" value="news" /> News <br />
<input type="submit" name="add" value="Save" />
</form>
<form>
<input type="check" id=chk1 value="1">
<input type="check" id=chk2 value="1">
<input type="check" id=chk3 value="1">
</form>
when you check on chk2 you can see values as:
<?php
foreach($_POST as $key=>$value)
{
if(isset($key))
$$key=strip_tags($value);
}
insert into table (chk1,chk2,chk3) values ('','1','');
?>
in BS3 you can put
<?php
$checked="hola";
$exenta = $datosOrdenCompra[0]['exenta'];
var_dump($datosOrdenCompra[0]['exenta']);
if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){
$checked="on";
}else{
$checked="off";
}
?>
<input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>
Please Note the usage of isset($datosOrdenCompra[0]['exenta'])
Wordpress have the checked() function.
Reference: https://developer.wordpress.org/reference/functions/checked/
checked( mixed $checked, mixed $current = true, bool $echo = true )
Description
Compares the first two arguments and if identical marks as checked
Parameters
$checked
(mixed) (Required) One of the values to compare
$current
(mixed) (Optional) (true) The other value to compare if not just true
Default value: true
$echo
(bool) (Optional) Whether to echo or just return the string
Default value: true
Return #Return
(string) html attribute or empty string
i have fixed it into a PHP form with a checkbox
$categories = get_terms( ['taxonomy' => 'product_cat', 'hide_empty' => false] );
foreach ($categories as $categorie) {
echo "<input type="checkbox" value="$categorie->term_taxonomy_id" name="catselected[]"> $categorie->slug";
}
This way i add it to the Woocommerce tabel.
wp_set_post_terms( $product_id, $_POST['catselected'], 'product_cat' );
filter_input(INPUT_POST, 'checkbox_name', FILTER_DEFAULT, FILTER_FORCE_ARRAY)
<?php
if(isset($_POST['nameCheckbox'])){
$_SESSION['fr_nameCheckbox'] = true;
}
?>
<input type="checkbox" name="nameCheckbox"
<?php
if(isset($_SESSION['fr_nameCheckbox'])){
echo 'checked';
unset($_SESSION['fr_nameCheckbox']);
}
?>
you should give name to your input .
then which box is clicked you will receive 'on' in your choose method
Array
(
[shch] => on
[foch] => on
[ins_id] => #
[ins_start] => شروع گفتگو
[ins_time] => ما معمولاً در چند دقیقه پاسخ میدهیم
[ins_sound] => https://.../media/sounds/ding-sound-effect_2.mp3
[ins_message] => سلام % به کمک نیاز دارید؟
[clickgen] =>
)
i have two checked box in my form name with 'shch' and 'foch'

PHP Radio Buttons - Keep The Values in The Form after an Error

I'm building a contact page with email, name, etc. in HTML with PHP. I have radio buttons on my contact page as well. If the user submitted their name and checked a radio button but forgot to put an email in, the form processing page will flipped them back to the contact page with an error. I'm able to have my contact keep the values put in for their name (and email if user inputs it), but it does not keep the value checked in the radio button.
I'm new to PHP, so I bet it's a silly error on my part. Here's what I have for my Name Input:
Your Name:
<input type="text" name="name" <?php
if (isset($form['name'])) {
echo 'value="';
echo htmlentities($form['name']);
echo '"';
}
?>/>
I tried to do something similar to my Radio. Here's what I have for my Radio:
Are you New to our Business?<br>
<input type="radio" name="customer" value ="yes" <?php
if (isset($form['customer'])) {
echo 'value="';
echo htmlentities($form['customer']);
echo '"';
}
?>/>
Yes, I am!<br>
<input type="radio" name="customer" value="no"<?php
if (isset($form['customer'])) {
echo 'value="';
echo htmlentities($form['customer']);
echo '"';
}
?>/>
No, I am a returning customer!
I'm storing the values on the user input in an array called $form - that's why I have ($form['name]). I would like to it to continue doing that. Some other responses I have researched simply have an isset without the array part.
Hopefully I've provided enough information... Thanks for your help!
You need to do it like this:
if (isset($form['customer']) && $form['customer'] == "yes") {
echo 'checked="checked"';
}
and
if (isset($form['customer']) && $form['customer'] == "no") {
echo 'checked="checked"';
}
You need to change the if-conditional to the following:
<?php
if (isset($form['customer']) && $form['customer'] == "yes") {
echo 'checked';
}
?>/>
Replace the "yes" with "no" for the No part.

how to handle checkboxes with statements and echo them

hello i have the following problem:
i would like to create a filter for a search engine. i have some inputfields for specific search terms and beside a respective checkbox. so that looks like:
inputfield a: [_____] filter for a: on/off: [ ]
inputfield b: [_____] filter for b: on/off: [ ]
inputfield c: [_____] filter for c: on/off: [ ]
the code structure of that is:
first of all check if the inputfield is empty and the checkbox is set checked. in case of checked it will be unchecked after submit. the other way around, if just the inputfield is filled and the checkbox unchecked, it also will error out, that there is a mistake and the filter can't work. so i'm using for each filter an own error array like (the name and value of the first checkbox is name="filter_a" value="1") :
...
$checkbox_filter_a = $db->real_escape_string(htmlentities(trim($_POST['filter_a'])));
...
$filter_a = (!empty($checkbox_filter_a)) ? 1 : 0;
...
$errors_a = array();
if ($filter_a == 1){
if (empty($input_a)){
$errors_a[] = 'the filter needs some input';
}
}
if (!empty($input_a)){
if ($filter_a == 0){
$errors_a[] = 'filter is not activated';
}
}
if there is no error and both criteria are fulfilled the filter either is on or not.
so the logical behind that is, when loading the page the checkbox have to be unchecked. after regarding the criteria to filter it is on.
to display the status checked or unchecked under the conditions below it should be checked after submit or either not. therefor i have this code for each filter (respective checkbox_filter_b, ...) the part of the checkbox after the inputfield:
<?php
if (checkbox_filter_a == 0 ) {
echo '<input type="checkbox" name="checkbox_filter_a" value="1" checked/>';
}else {
echo '<input type="checkbox" name="checkbox_filter_a" value="1"/>';
}
?>
what does not satisfy at all. this is because of the following problem:
when loading the page it will show all checkboxes are unchecked. if i try to cause an error because of no filled input or just checked checkbox for one of these filters, after submit all other checkboxes are automatically checked.
so if there is someone who could help me out i really would appreciate. thanks a lot.
Perhaps you could do it this way, by defining default values for your check boxes and values at the start of your script. Then change them with the values of the POSTed if there set or not.
<?php
//Setup Variable Defaults, if POST dont change them then there no complicated ifelse's
$filter_a=null;
$checkbox_filter_a='<input type="checkbox" name="checkbox_filter_a" value="1"/>';
$filter_b=null;
$checkbox_filter_b='<input type="checkbox" name="checkbox_filter_b" value="1"/>';
$filter_c=null;
$checkbox_filter_c='<input type="checkbox" name="checkbox_filter_c" value="1"/>';
//Check for post
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//If the check box is not checked checkbox_filter_a will fail this part
// so $filter_a will still be null
if(isset($_POST['filter_a']) && isset($_POST['checkbox_filter_a'])){
$filter_a = trim($_POST['filter_a']);
$checkbox_filter_a ='<input type="checkbox" name="checkbox_filter_a" value="1" checked/>';
}
if(isset($_POST['filter_b']) && isset($_POST['checkbox_filter_b'])){
$filter_b = trim($_POST['filter_b']);
$checkbox_filter_b = '<input type="checkbox" name="checkbox_filter_b" value="1" checked/>';
}
if(isset($_POST['filter_c']) && isset($_POST['checkbox_filter_c'])){
$filter_c = trim($_POST['filter_c']);
$checkbox_filter_c = '<input type="checkbox" name="checkbox_filter_c" value="1" checked/>';
}
}
echo <<<FORM
<form method="POST" action="">
<p>Inputfield a: <input type="text" name="filter_a" value="$filter_a" size="20"> filter for a: on/off:$checkbox_filter_a</p>
<p>Inputfield b: <input type="text" name="filter_b" value="$filter_b" size="20"> filter for b: on/off:$checkbox_filter_b</p>
<p>Inputfield c: <input type="text" name="filter_c" value="$filter_c" size="20"> filter for c: on/off:$checkbox_filter_c</p>
<p><input type="submit" value="Submit"></p>
</form>
FORM;
//now here all you have to do is see if these values are not null and build your query
echo $filter_a.'<br />';
echo $filter_b.'<br />';
echo $filter_c.'<br />';
?>

radio button value in php

I'm trying to make a simple survey in php
I have a set of radio buttons on a page called sja.php that sends its to sjamail.php page
the problem is that when I go to get
$answer = $_POST['ans'];
I can't seen to do anything like
echo "$answer";
but if I were to throw some logic at it
like
if ($answer == "ans1") {
echo 'Correct';
}
else {
echo 'Incorrect';
}
It will display correct or incorrect (edit: The if/else works correctly and will display the correct answer )
so why is it I can't access the value of the radio button "ans" as a string?
http://www.markonsolutions.com/sja.php
print_r($_POST); will return Array ( [ans] => )
Perhaps the value is something other than text.
Try
var_dump($answer);
or
print_r($answer, TRUE);
Your page works correctly if you select any of the first 4 radio buttons (ans1/2/3/4). But the rest of the radio buttons next to all those images have blank values, which would explain why your posted value is empty if you selected any of those to test with.
You need to make sure that the field in HTML has...
<input type="radio" name="ans" value="ans1" />
<input type="radio" name="ans" value="ans2" />
Also make sure your form method is POST
I had a similar problem with the following:
<input name="03 - Gender" type="radio" value="Masculino"/>Male<br/>
<input name="03 - Gender" type="radio" value="Femenino" required="required"/>Female <br/>
<input type="hidden" name="03 - Gender" value=""/>
but when I removed the third input line (the hidden one) the problem desapeared.
Try this:
$answer = (string)$_POST["ans"];
echo $answer;
You must convert $_POST["ans"] to string.

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