mardi 26 juillet 2016

Using On/Off Checkbox Sliding Switch to Run SQL Query

I am using a simple On/Off sliding switch to update a field in my database.

I turn it "on" no problem, but allowing the user to turn it "off" seems to be giving me trouble. I have multiple switches on this page, so whenever I "submit" it will turn "on" values to "off" unless I remove the elseif statement.

It seems the code considers the $_POST['check-twitter'] to be "isset" when it is on, but "!isset" when I switch it from on to off.

If I change my code to instead be "elseif(!isset....)" then when I come to the page again, it does not recognize the "on" position as being "isset" so it automatically turns it off. It seems inconsistent to what is considered "isset" and "!isset".

I want the switch to only update the database when the user changes it, and I need the switch to show the user whether it is "on" or "off."

// $twitter_check represents the field from the database which equals 'Yes' or 'No'

<label class="switch">
  <input type="checkbox" name="check-twitter" <?php echo $twitter_check == 'Yes'?'checked':''; ?>>
  <div class="slider"></div>
</label>

if(isset($_POST['check-twitter']) && $twitter_check == "No"){
    //SQL UPDATE $twitter_check = 'Yes'
    } elseif(isset($_POST['check-twitter']) && $twitter_check == "Yes") {
    //SQL UPDATE $twitter_check = 'No'
    }

<input class="button" type="submit" name="submit" value="Save"/>




Aucun commentaire:

Enregistrer un commentaire