Passing the value using checkbox with html and php - 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');
}

Related

How to access two different values for one checkbox?

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

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 checkboxes that return display and return "Yes" from a database

I am building a site with a number of independant check boxes that collect information about industry topics. I user will check the ones of interest and store “Yes” in the database which is Filemaker.
When they return, they will see the ones previously checked and can uncheck if needed.
To this end, I am trying to get a check box to display as checked if the database value is equal to “Yes” and display as unchecked if the value is blank. Also, of the user checks the checkbox on the form, it will send the value of “Yes” back to the database and a value of blank if the check box is unchecked.
So far, I am only able to display the “Yes” or blank for fields. Here is my code so far:
<input type="text" name="Core_Compentencies__Marketing" value="<?php echo $port_row->getField('Core_Compentencies::Marketing'); ?>"></td>
Any help is appreciated.
Thanks.
usually i use helper function to decide whether field value is checked or not.
<?php
function isChecked($value = '', $defaultVal = 'Yes')
{
if($value == $defaultVal)
{
return 'checked';
}
}
?>
<input name="checkbox" type="checkbox" value="Yes" <?php echo isChecked(Core_Compentencies::Marketing); ?>>

check if checkbox is checked in php

I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>

How to retrieve the checked state of a checkbox from a Html form and store it in a database?

i have a form field
<input type="checkbox" name="page" value=""/>
and corresponding field in mysql db is true and false, if someone click the checkbox i would like to send TRUE value to db via POST, how do i achieve it ?
You give the input any value you like:
<input type="checkbox" name="page" value="true"/>
Then, if the checkbox is checked, it will be a successful control and submitted.
<?php
if (isset($_POST['page']) && $_POST['page'] == 'true') {
// Then insert something into the database as normal
}
?>
If you want to set it when the checkbox is not ticked, then you will need an else to go with the if.
For a checkbox, the value attribute determines what the value will be if the item is checked. If it isn't checked, then no value will be submitted at all. You should therefore always specify the value attribute on a checkbox.
If you want the checkbox to default to checked, then you also need to specify the checked attribute.
<input type="checkbox" name="page" value="1" checked='checked' />
The Form:
<form action="/path/to/processing_script.php" method="POST">
<!--... Other Form Elements go here -->
<input type="text" name="color" />
<input type="checkbox" name="page" value="True"/>
<input type="submit" value="Send to Database" />
</form>
Processing script:
(processing_script.php)
<?php
// Check is 'True'?
if ($_POST['page'] != 'True')
{
$_POST['page'] = 'False';
}
$con=mysqli_connect("your-db-loc","your-db-username","your-db-pass","db-name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL Database: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO TableNameHere (True-false, Favorite Color)
VALUES ($_POST['page'], $_POST['color'])");
mysqli_close($con);
?>
This example I created add's 2 data types to a new row on the database.
Replace the text 'TableNameHere' with your db table name, should be in similar format to: 'prefix_colors_tble'
Replace the text "your-db-loc" with your databases location, usually 'localhost' for internal server, or could be a URL for live server.
Replace the text "your-db-username" the username used to login to mysql, must have sufficient privileges.
Replace the text "your-db-pass" the user's password
Replace the text "db-name" database name (not deemed important unless containing multiple databases)
Replace the text "True-false" & "Favourite Color" with your db table column headings as appropriate.
Good Luck! -p.s. I know this answer is a few years late, but I hope it can help somebody else. Send your appreciation to http://amazewebs.com/testimonial Thanks.
Collect the follows by reading $_POST after form submission, then write them to the database using mysql_query
the first thing you will have to do is to modify the current html code for checkbox and add something in the value field.
let say you set the value to 1.
The second thing is if you are posting the form, then you will have to process the form using a server side language like PHP,Perl, Java etc.
for e.g. in PHP you can get the catch what is sent for the page field using $_POST['page'].
Now you will have to do a bit of server side processing to see if the $_POST['page'] == '1' , then set $page = 'true';else set$page = 'false';
the you can insert the $page into the database by using the library functions of the language you are using.

Categories