checkbox status "checked" by default problem - php

I have a page with search form on it and table with search results below. In search form i have checkbox "Search in this category". What i'm doing to check it by default :
if(!isset($_SESSION['inthiscat'])){
$_SESSION['inthiscat'] = 'on' ;
$checked = 'checked';
}
$_GET['inthiscat'] = $_SESSION['inthiscat'];
checkbox code : INPUT type="checkbox" name="inthiscat"<?=$checked?>.
Link to next page of results index.php?inthiscat=$_GET['inthiscat'].
So the problem is when i uncheck "Search in this category" its still checked when i going to next page of results. How to fix it and what i'm doing wrong? Session startet of course.

Firstly, do you really need SESSION variables for this? If you want box to be checked when GET parameter is not specified, you do not need SESSIONs at all.
Assuming you want to preserve the behaviour in case someone removes the GET parameter:
<?php
session_start();
//......
//......
$checked='checked';
if(isset($_REQUEST['inthiscat'])) {
// Form input and url GET parameters take precedence
if($_REQUEST['inthiscat'] != 'checked') { $checked = ''; };
} else if(isset($_SESSION['inthiscat'])) {
// Next, use session variable if it exists
if($_SESSION['inthiscat'] != 'checked') { $checked = ''; };
};
$_SESSION['inthiscat']=$checked;
?>
Note:
1) Assigning values to GET array is not a good practice.
2) I assume you are using correct syntax for your FORM submit.
3) IMO, you could remove the SESSION variable as you are explicitly passing as GET parameter in the subsequent urls. Or dont use the GET parameter in urls.

Problem is: when you uncheck the checkbox and go to the next page, $_SESSION['inthiscat'] will still be unset - where did you change it?
Here is the code:
if (isset($_GET['inthiscat'])) {
$_SESSION['inthiscat'] = $_GET['inthiscat'];
}
if (!isset($_SESSION['inthiscat'])) {
$checked = 'checked';
} else {
if ($_SESSION['inthiscat'] == 'on') {
$checked = 'checked';
} else {
$cheked = '';
}
}
Assuming this HTML: <INPUT type="checkbox" name="inthiscat" checked="<?=$checked?>" value="on" />
So what it does is:
Looks for the GET data and, if there is, assigns it (can be 'on' or '') to the SESSION;
If there is no SESSION (that means, no GET as well) it's the first page of that kind the user visits, so checked;
If there is a SESSION for inthiscat, it means it's not the first page and GET data has been assigned to the SESSION. So, if it's on, it displays the mark; else, it does not.

Related

Checked box should stay checked PHP

if i check the checkbox, the checkbox should stay checked. I got a form where it gets checked after submit, but it should staying checked without any Submit. is it possible with php?
Code:
$checkbox=false;
if (isset($_POST['psp-ele'])){
$checkbox=true;
};
?>
<input type="checkbox" name="psp-ele" id="Investnr" class="Investnr" <?php if ($checkbox==true) { echo "checked='checked'";}; ?> >
If you want the checkbox to stay checked when you load the page without a form submit then you should keep that information in the session and set the value from the session when parsing the checkbox:
In your form processor:
session_start();
$_SESSION['psp-ele'] = isset($_POST['psp-ele']);
Where ever you want to parse it:
<?php
// start the session if it has not already been started
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
?>
<input type="checkbox" name="psp-ele" id="Investnr" class="Investnr" <?php if ($_SESSION['psp-ele']) { echo 'checked'; }; ?> >
The initial load of your page that contains the form is likely to happen via a GET request - so simply add a check if the request method was GET, and also set your flag to true in that case:
$checkbox=false;
if ($_SERVER['REQUEST_METHOD'] == 'GET' || isset($_POST['psp-ele'])){
$checkbox=true;
};
If you want the form to be checked by default and after submit want to persist the users selection then you can simply add another condition which checks if the variable has been defined or not with isset.
if(!empty($_POST)){
if (isset($_POST['psp-ele'])){
$checkbox = true;
}else{
$checkbox = false;
}
}
<input type="checkbox" name="psp-ele" id="Investnr" class="Investnr" <?php if (!isset($checkbox) || $checkbox) { echo "checked='checked'";}; ?> >
The isset checks the checkbox when loading for the first time and the $checkbox variable does it after being submitted.

chaining if else statements

I have a form field in my website which i use for a table in my database. i'm using checkboxes for a true/false value. In my case my checkboxes send out an empty string if left unchecked.
I made an if else statement to make sure the empty string is made boolean. however, my if else statements only works for the first one ($ringe). the last two ($halskaeder and $armbaand) does not seem to work, as my database does not register any inputs.
I'm guessing my if else statements has flaws or syntax errors, i'm just too hopeless at PHP to figure out what's wrong.
if ($_REQUEST['ringe'] == ""){
$ringe = '0';
}
else {
$ringe = '1';
}
if ($_REQUEST['halskaeder'] == ""){
$halskaeder = '0';
}
else {
$halskaeder = '1';
}
if ($_REQUEST['armbaand'] == ""){
$armbaand = '0';
}
else {
$armbaand = '1';
}
Any help is highly appreciated!
UPDATE!!!
So I realized my issue is that an unchecked checkbox in html doesn't send and signal. So i have to change that no matter what
AFAIK the check box is not sent if it's not checked. You can do something like:
$default = array(
'ringe' => 0,
'halskaeder' => 0,
'armbaand' => 0,
);
$myFormParams = array_replace($default, $_REQUEST);
var_dump($myFormParams);
few Suggestions... I may add more if you post your form..
1) Trim whitespace from user input (unless you need it)
$input = trim($_REQUEST['user_input']);
2) In this case, you should use empty(), because this function checks to see if the variable exists, and if it's empty, and if it's falsy. You can kill three birds with one stone.
3) Use ternary. It's shorthand for what you're doing.
$input = trim($_REQUEST['user_input']);
$input = empty($input) ? "0" : "1";
I found an answer. My problem wasnt the php code, but the checkboxed not sending any input when unchecked. The workaround is simply putting a hidden input field to send a false signal no matter what. You give it the same name attribute as your real checkbox, which will override when checked.
looks like this:
<input type="hidden" name="ringe" value="0" /><input type="checkbox" name="ringe" value="1" /><p>Ringe</p>
thanks for the help though!

Re-populate checkbox if it fails in validation in an edit form in Codeigniter

I works on the an data-edit form in codeigintier. And the problem is about re-populate checkbox
It works if it is an add form (that means I need not concern about the value in database):
<?= set_checkbox('is_default', '1'); ?> for checkbox
The problem is, in the edit form:
I can't repopulate the checkbox
<?php if ($customer_group[0]['is_default'] == "1") echo "checked"; set_checkbox('is_default', '1'); ?>
The checkbox will check even I have not check it in the edit => fail to validate in the form, thanks for helping
I have already set the validation rule in controller, the code in the add form is working , but how to handle the case for edit form?
In order to re-populate checkbox following code might be helpful:
set_checkbox('fieldName', 'fieldValue');
Where 'value' is the second parameter of the form_checkbox call. Like this:
form_checkbox('fieldName[]', 'value', set_checkbox('fieldName', 'value'));
Now if you are on edit form then below code might help you
$getVal=$valFromDb; //$valFromDb is actually value of the filed from db as you are on edit page
if($getVal!=0){
{
echo form_checkbox('fieldName[]', 'value', true);
}
else
{
echo form_checkbox('fieldName[]', 'value', false);
}
set_checkbox takes a third argument to set the default state, so basically you have to do something like this
echo set_checkbox('is_default', 1, $customer_group[0]['is_default'] == "1");
Can give one suggestion??
1. Hide all the checked value of checkbox in input box when you are directed towards edit page.
If checked box is checked in edit page, edit the value of hidden input field of textbox value.
Submit it, when validation failed, checked or repopulate the checkbox value according to hidden field value. send checkbox value of checked box field through array from controller to edit page view like this. e.g $data['repopulate_checks'] = $this->input->post('array name of checkboxs');
In view :
getit like this
$catch_checkbox = $repopulate_checks;
You can directly get through $repopulate_checks also.
Hope this help you.
You can use form_checkbox() function: Guide
$isChecked = False; // or True for default value
If have stored data then:
$isChecked = $customer_group[0]['is_default'];
echo form_checkbox('input_name', 'value', $isChecked);
or the hard way:
set_checkbox():
The first parameter must contain the name of the checkbox, the second
parameter must contain its value, and the third (optional) parameter
lets you set an item as the default (use boolean TRUE/FALSE)
<input type="checkbox" name="is_default" value="1" <?php echo ($customer_group[0]['is_default']) ? set_checkbox('is_default', '1') : '' ; ?>/>
set_checkbox takes a third argument to set the default state, so basically you have to do something like this
$checked = FALSE; if($customer_group[0]['is_default']){ $checked = TRUE; }
echo set_checkbox('is_default', 1, $checked);

php function that checks if checkbox is selected. Field validation issue

Please read my issue carefully, it's a bit tricky.
The function below is used to display whether a checkbox has been checked in a form on both of my 'add' and 'edit' record pages. No problem here.
The problem:
Let's say I have 2 fields 'name' and 'enabled'. Only fields that is validated is 'name'.
When a user edits an existing record and enters an invalid 'name', the form gets validated. If the user un-checked the 'enabled' checkbox (prior value was $field_record_value="1", setting from the database), the checkbox value still set as "1" as it's still coming from the database.
Question:
How do I get the value to set as "0" when the database record ($field_record_value) is set to 1 ?
I know the issue lies in this code:
$is_checked = isset($field_record_value) ? $field_record_value : '0';
I can't seem to figure it out, maybe because I've spent about 2 hours on this and my brain is fried..but I digress :)
//------------------------------------------------
// Function to check if checkbox is selected
//------------------------------------------------
function form_checkbox_selected($field_name, $page = 'add', $field_record_value = '0')
{
if(!empty($_POST[$field_name]) && intval($_POST[$field_name]))
{
$is_checked = '1';
}
else
{
if($page ==' edit')
{
$is_checked = isset($field_record_value) ? $field_record_value : '0';
}
else
{
$is_checked = '0';
}
}
return $is_checked;
}
The problem is that you are expecting an unchecked value for a checkbox, the browser will never send a value for an unchecked checkbox, so the only way you can know a checkbox is in it's unchecked state is by assumption, which you can only assume after the form has been submitted. I would rewrite your function like so:
function form_checkbox_selected /// line wrapped for SO read-ability
($field_name, $page = 'add', $form_submitted = false, $field_record_value = '0'){
if ( form_submitted ) {
$is_checked = !empty($_POST[$field_name]) ? 1 : 0;
}
else if ( $page == 'edit' ) {
/// isset is not required because it will always
/// be defined by $field_record_value = '0' in default params.
$is_checked = $field_record_value ? 1 : 0;
}
else {
$is_checked = 0;
}
return $is_checked;
}
In order to tell if the form has been submitted or not, it is usually best to have a hidden field that you know will always be sent, or you can define a name for your submit button.
<form>
<input name="sent" type="hidden" value="1" />
</form>
<form>
<input name="sent" type="submit" value="Submit Form" />
</form>
Then on the php side you can call your function:
form_checkbox_selected(
'my_field', 'edit', !empty($_POST['sent']), $db['my_field']
);
This now means your php can make a better assumption of what the field's state is when no data has actually been passed in.

Passing the value using checkbox with html and php

I have two forms
a) post.php
b) edit.php
I am using the checkbox in both the form to set the binary value (0 and 1) to set the status for approve.
to process the value from the checkbox in the post.php I am using the code which checks and assume that if the checkbox is checked then the value will be 1 other wise it is 0 by default
if (isset($_POST['ad_approve'])) $ad_approve = htmlspecialchars(strip_tags(mysql_real_escape_string($_POST['ad_approve'])));
else { $ad_approve = 0; }
Now in the edit.php form I retrieve the data from the database and set the checkbox accordingly . if the approve has the value 1 then it is checked by default . look onto the following code
<input name="ad_approve" type="checkbox" value="1" <?php if($approve==1) echo 'checked="checked"';?> />
in the above code I cannot apply the same logic to catch the value from ad_approve i.e(by checking isset()) because if the value is 1 by default and if I try unchecking the checkbox then automatically the program assume that the value is set because it has been changed from checked to unchecked. now in the edit.php how do I again process the value from it such that if the checkbox is checked hold the value as 1 otherwise 0, ??
to be honest your question does not make a whole lot of sense but I can understand that you wish to check if check boxes are actually set.
firstly you don't need a value attribute on a check box because its the browser that decide what value if any to send via the GP headers.
http://www.w3.org/TR/html401/interact/forms.html
Checkboxes (and radio buttons) are
on/off switches that may be toggled by
the user. A switch is "on" when the
control element's checked attribute is
set. When a form is submitted, only
"on" checkbox controls can become
successful.
So basically if a checkbox is not selected then the entity will not be sent via the headers, there for isset() would be a perfectly usable check.
The way your using real escape is totally wrong, you should never user real escape for html, DATABASE ONLY.
Take this code for example
if(isset($_POST['some_check']))
{
echo $_POST['some_check']; //on
}else
{
echo 'some_check has not been checked';
}
Your code:
if (isset($_POST['ad_approve'])) $ad_approve = htmlspecialchars(strip_tags(mysql_real_escape_string($_POST['ad_approve'])));
else { $ad_approve = 0; }
Can you give me a good excuse why your using htmlspecialchars,strip_tags and mysql_real_escape_string on an entity that can be done like so:
$ad_approve = isset($_POST['ad_approve']) ? true : false;
for issues like this its not that hard to refer to the documentation to get a better understand of what exactly is being sent from the browser.
if you wish to add values to to the checkboxes that you would do this with hidden fields, example follows.
<input type="checkbox" name="check_box" />
<input type="hidden" name="check_box_value" value="01100001" />
And within the php server side.
if(isset($_POST['check_box']))
{
echo $_POST['check_box_value']; //01100001
}else
{
echo 'some_check has not been checked';
}
by adding another html input thats hidden you can hide elements from the user and then use as data holders, the reason why you should use the exact same name but append it with _value is just for best practises.
EDIT
if(isset($_POST['some_check_box']))
{
mysql_query('UPDATE profile SET receive_mail = 1');
}else
{
mysql_query('UPDATE profile SET receive_mail = 0');
}

Categories