-1

I've this code to submit a query to mysql database, it's a switch ON/OFF, but when switch ON works perfect when switch OFF it does not works.

Any help please...

<?php
if(isset($_POST['onoffswitch'])){
$check_fospp=$_POST['onoffswitch'];
if ($check_fospp==on) {
    // code...
    $check_fospp=1;
}else{$check_fospp=0;}
echo "Test.. $check_fospp";
sleep(3);
//run code mysql update......
}

?>

<form name="fanc5" action="" method="post">
<div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" tabindex="0" onchange="document.fanc5.submit()" <?php if($check_fospp=="1"){echo "checked";}?>>
    <label class="onoffswitch-label" for="myonoffswitch">
        <span class="onoffswitch-inner"></span>
        <span class="onoffswitch-switch"></span>
    </label>
</div>
</form>
ADyson
  • 57,178
  • 14
  • 51
  • 63
Bruno
  • 15
  • 3
  • You are checking `if` the value is `on` only if the value is set. If the value if off, it is not set on form submit (If I recall correctly) so the first `if` prevents it from entering the rest of the `if/else` check – blurfus Jun 07 '22 at 14:00

1 Answers1

0

In HTML forms, a checkbox only submits a value at all if it's checked. So when the checkbox is unchecked, no field is submitted in the POST data, therefore your isset would return false there, and not enter the block which sets the on/off status at all.

This simpler logic:

$check_fospp = (isset($_POST['onoffswitch']) ? 1 : 0);

is likely to work better.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • I need to switch on or switch off something, If checkbox only submit a value if it's checked this is not the better solution for my scenario... I've tried: '''$check_fospp = (isset($_POST['onoffswitch']) ? 1 : 0);''' – Bruno Jun 07 '22 at 14:36
  • `if checkbox only submit a value if it's checked this is not the better solution`....why not? If the checkbox is submitted, then you know it's "on". If the checkbox isn't submitted then you know it's "off". The checkbox only has two states, so you can easily tell which one is on or off. Why do you think that is a problem? – ADyson Jun 07 '22 at 14:37
  • I've not a submit button, all works directly whit the onchange="document.fanc5.submit()", so when I switch off I've not data on the form.... – Bruno Jun 07 '22 at 14:40
  • So what? `document.fanc5.submit()` is the exact equivalent of pressing a submit button. Therefore, if the checkbox is un-checked when it changes, it will be submitted unchecked, and therefore your PHP can detect that and decide that the status is "off". – ADyson Jun 07 '22 at 14:42
  • https://stackoverflow.com/questions/12115373/detect-unchecked-checkbox-php - the answers there are suggesting the same solution as me. – ADyson Jun 07 '22 at 14:52
  • Thank you!! That post contain the perfect solution!! – Bruno Jun 07 '22 at 15:31