i have 2 checkbox that deliver the different value..
<input type="hidden" name="position[]" value="<?php echo $excheck['check_id']; ?>">
<input name="position[]" class="checkbox" type="checkbox" <?php if($pos == $poss) echo 'checked = "checked"'; ?> value="<?php echo $eq['pos_unit_name']; ?>">
its for determined whether it is checked or not..
if it not checked , then the value is still delivered which is the check_id..
the problem is, if another checkbox is checked, and the current checkbox is remain, how do i add the code?
this is currently my code..
$check = $_POST['position'];
foreach ($check as $id)
{
if(is_numeric($id))
{
$up = mysql_query("delete from checklist where check_id = $id");
}
}
what i want to accomplish is , if its unchecked, the data is deleted based on the check_id and if another checkbox is checked , insert a new data, and if the checked box is remain checked, then it just updated the value based on the check_id
First need to use unique name for each form fields. you have two fields name as position so use different name
and query var should be quoted like
$up = mysql_query("delete from checklist where check_id = '$id'");
What you want to do in this case is to add the identifier as the key:
<input name="position[<?php echo $excheck['check_id']; ?>]" value="1" />
And then:
foreach ($_POST['position'] as $id => $checked) {
// do stuff with $id
}
Related
I have a program where I am populating the check box, once I click on the submit button, I am inserting the data into DB and I want to retain the checkbox state as checked for the values that I have inserted, so that when a user logs in again he can see the items he has checked the previous time. This is my code
<?php
$accQry = "select * from brands";
$result1 = mysql_query($accQry, $db1->conn);
$i = 1;
while ($row = mysql_fetch_assoc($result1)) {
?>
<label> <input type="checkbox" value="<?php echo $row['brand_id']; ?>" name="chk1[]" ><?php echo $row['brand_name']; ?></label>
<?php $i++;
}
?>
This is the code to populate and I don't know how to go about it further.
Checkbox has attribute checked, which should be set when you want to check it - how checkbox works
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'
Basically I am trying to update my database with multiple values. Input fields are in a loop, so I need to update multiple checkboxes and textboxes at the same time.
$cityID = $_POST["cityID"];
$cityStatus = $_POST["cityStatus"];
$cityOrder = $_POST["cityOrder"];
$updateCities = $db->execute("UPDATE cities SET city_status=?, city_order=? WHERE city_ID=$cityID", array($city_status, $cityOrder));
foreach($cities as $row) :
?>
<input type="checkbox" name="cityStatus[]" value="1">
<input type="text" name="cityOrder[]" value="<?php echo $row->city_order ?>">
<input type="hidden" name="cityID" value="<?php echo $row->city_ID; ?>">
What i understood is
1. you have array of 3 fields (cityid, cityorder, city status)
2. you are submitting all these values from the form
3. you want update cityorder and citystatus depends on cityid
The solutions is pretty simple
$i=0;
foreach($_REQUEST['cityOrder']) as $cityorder){
$cityID = $_POST["cityID"][$i];
$cityStatus = isset($_POST["cityStatus"][$i])?$_POST["cityStatus"][$i]:0;
$cityOrder = $_POST["cityOrder"][$i];
$updateCities = $db->execute("UPDATE cities SET city_status=?, city_order=? WHERE city_ID=$cityID", array($city_status, $cityOrder));
$i++;
}
As the title reveals I got an issue with how to update a checkbox that already has data in my SQL database.
My code looks like following:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name <input type"text" name="inputName" value="<?php echo $hemsida['Namn']; ?>" /> </br>
Commentar <input type"text" name="inputComment" value="<?php echo $hemsida['Comment']; ?>" />
<br/>
</br><input type="checkbox" name="inputAll" value="checked" <?php echo $hemsida['All']; ?>/>Alla
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Redigera">
<?php
if(isset($_POST['submit'])) {
$u = "UPDATE hemsida SET `Namn`='$_POST[inputName]', `Comment`='$_POST[inputComment]', `ALL`='$_POST[inputALL]' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User has been modified";
header("Location: ..//sokh.php");
}
?>
The echo $hemsida['Namn'],['Comment'], and ['All'] just brings up and shows the old data thats in the database, but I do not understand what to do to update the checkbox. I have looked everywhere but I am stuck. Thank you in advance!
If I understand your question correctly, you are looking for a way to have a checkbox be either checked or not checked depending on database info. If so, I would try something like this. At the top of your code where you get your database info, put
if($conditionForCheck){
$inputAll = ' checked="checked"';
}
Then in your form
<input type="checkbox" name="inputAll"<?php echo $inputAll; ?> />
your question is not clear but i think you have a column in your database named "all" ? and perhaps this column can take only 1 value (true or false) !!
then you can test this value in your form, if the value is true : checkbox will be checked, else : checkbox will not be checked :
<input type="checkbox" name="inputAll" checked="<?php if($hemsida['All'] == true) echo checked; ?>" />Alla
dont use value="", use checked instead, then test value of $hemsida['All'] if it's true echo checked else anything to do
for your php code and server side of your application you can just test if checkbox is checked and then you have choice for what do you want to assign to your column in database, for example if checkbox is checked create a variable (for example $value_of_checkbox) and assign a value ("true" for exampel) to this variable, then include this variable in your sql code for update database column :
if (isset($_POST['inputALL'])) {
$value_of_checkbox = true;
}
else {
$value_of_checkbox = false;
}
if(isset($_POST['submit'])) {
$u = "UPDATE hemsida SET `Namn`='$_POST[inputName]', `Comment`='$_POST[inputComment]', `ALL`='$value_of_checkbox' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User has been modified";
header("Location: ..//sokh.php")
note : i change also sql code in this part : ALL='$value_of_checkbox'
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'