How to access two different values for one checkbox? - php

I'm using HTML, PHP, jQuery for my website.
I've a check box on my form as follows:
<input type="checkbox" name="check_status" id="check_status" value="1"> Status
I want the same check box for two different values. In short, after submission of the form if check box is checked I should get the value 1 in $_POST['check_status'] array and if the check box is unchecked at the time of submission of form I should get the value as 0 in $_POST['check_status'] array after form submission.
Now as per the above HTML code if check box is checked I'm getting value 1 and if the check box is unchecked then I'm getting blank value.
How should I resolve this issue to achieve the desired result?

You can add condition in php. Hope this will help.
if(isset($_POST['check_status'])) {
$status = $_POST['check_status'];
} else {
$status = 0;
}
echo $status;

you can use this
$status = 0;
if(isset($_POST['check_status'])) {
$status = 1;
}
echo $status;

In case you really need those values to be send as 1 and 0 to the server ( maybe you can't change the server-side code), you can add a hidden field with the same name as your checkbox, and then use JavaScript/jQuery to fill that hidden field, before you submit the form, with 1 or 0, for checkbox being checked, respectively unchecked. .
$("#hiddenField").val( $('#checkbox').is(':checked') ? 1 : 0 );

Related

Submitting a dynamic checkbox form and get values in pairs

I have a form with dynamically added checkboxes - each checkbox together with a hidden field. I need only the checked values displayed in pairs with the hidden field when submitted.
This is what I have:
<input type="checkbox" name="valg[]" value="<?=$hent_data[id]?>" />
<input type="hidden" name="process_id[]" value="<?=$hent_data[process_id]?>" />
<?php
if($_POST[submit] != ""){
$arrlength=count($_POST[valg]);
for($x=0;$x<$arrlength;$x++) {
$dimen1 = $_POST[valg][$x];
$dimen2 = $_POST[process_id][$x];
echo $hest = "INSERT INTO chosen (kat_ref, prod_ref, process_id) VALUES ($dimen1, '', $dimen2)"."<br/>";
}
}
?>
When submitted I get the correct number of rows as I have checked, with the correct checkbox value, BUT, the problem is in the hidden text input. On submit it lists all hidden values.
Let's say in a form with 10 checkboxes (and hidden text input) I have ticked 3 checkboxes I would want the exact 3 hidden text input boxes to be listet together with the ticked checkboxes, but it returns them all, which means that no matter how many checkboxes I check, it'll still parse all the hidden value fields.
Any ideas?
I hope you understand - or else let me know ;-)
From the discussion, to me it seems better to send the checkbox in key=>value
<input type="checkbox" name="valg[<?=$hent_data[id]?>]" value="<?=$hent_data[process_id]?>" />
This will give you a result in the php side similar to
Array
(
[valg] => Array
(
[uniqueKey3] => processID3
[uniqueKey7] => processID7
[uniqueKey8] => processID8
)
)
Therefore in the php you can do this:
foreach($_POST['valg'] as $ID => $processID){
echo $hest = "INSERT INTO chosen (kat_ref, prod_ref, process_id) VALUES ($ID, '', $processID)"."<br/>";
}

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

I need assistance preventing both a checked and unchecked checkbox from posting at the same time

I have created a table of checkboxes. The rows are divided up by category, and either a checked or unchecked checkbox gets displayed under a department column. I have a lot of code so I will break down what I am supplying. I am creating an array via each column (odd method, yes). I have noticed that if all check boxes are deselected, it will return the hidden value of 0 each time it loops. Thats great, thats what I wanted. However, if the box is selected, it returns both the value of 0 and the value of 3. For instance:
Test = Array()
Test[0] => 0
Test[1] => 3
How can I prevent it from posting the hidden value?
$row_two = mysql_query("SELECT dept_id FROM categories WHERE cat_name = '{$cats['cat_name']}' and bus_id = '{$busUnits['bus_id']}'");
while (($test_two=mysql_fetch_assoc($row_two)))
{
$AnotherTest = implode(',', $test_two);
$WhatTest = explode(",", $AnotherTest);
if(in_array("3",$WhatTest, TRUE))
{
echo '<input type="hidden" name="Cat_CBC_Test_One[]" value="0">';
echo '<td><input type="checkbox" name="Cat_CBC_Test_One[]" value="3" checked></td>';
}
else
{
echo '<input type="hidden" name="Cat_CBC_Test_One[]" value="0">';
echo '<td><input type="checkbox" name="Cat_CBC_Test_One[]" value="3"></td>';
}
To detect unchecked Checkboxes i would add a hidden field with a different name, like _Cat_CBC_Test_One. That way you dont have the issue with the hidden field interfering.
Then, on the server, you scan through for parameters that start with _ and add the missing "false" Parameters for further processing.

how to save checkbox value into mysql database using php

hi i have a form which has a checkbox and i want to save the value of the checkbox into my database but when i click on the checkbox and save it it works fine and when i try to save the form without checking on the chekbox it shows undefined index can any one help me out
here is my html
<input type="checkbox" name="active" value="1"></input>
here is my php
$nactive = $_POST["active"];
here is my save part
mysql_query("INSERT INTO `usermain`( `username`, `password`, level, active,`zimname`, zimmob, `email`, admin, makhtab)
Values
('$nuser', '$npwd', '$nlevel', '$nactive', '$nzname', '$nzmob', '$nemail', '0', '$makh')") or die(mysql_error());
If the checkbox isn't checked, the browser won't actually send the data in your POST request. You'll need to check if the value is set, and then update your variable accordingly.
$inactive = isset($_POST["active"]) ? $_POST["active"] : 0;
If the checkbox is not checked, the value is not posted to the script. You must check if it is set before using it.
if(isset($_POST['active'])){
//do something if is
}
else{
//do something if not
}
Use an isset control in the next page like this :
if (!isset($nactive)) $nactive = 0;
If your checkbox isn't checked, the value will be 0

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