Home » Php » php – Update checkbox value to database

php – Update checkbox value to database

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to update my database entry with an 1 or 0 depends on it is checked or not.

My current code looks like this (only one checkbox, the others are the same just other name):

<form method="post" action="" name="form">
  <label class="switch"><input type="checkbox" name="csgo" value="1"><span class="slider"></span></label> CSGO;
  <input type="submit" value="Save" class="btn btn-primary" name="submit">
 <?php
   $csgoac = isset($_POST["csgo"]) ? $_POST["csgo"] : 0;
   $sql = "UPDATE Users SET csgoactive='".$csgoac."' WHERE ID='1'";
   mysqli_query($db, $sql);
 ?>
</form>

I tested it with echo $csgoac; (before the query) and the output was checked = 1 and not checked = 0.

With the query now, it is only updating “0” to the database, what I did wrong on there?

How to&Answers:

Of course, the first time the page is rendered, $csgoac is 0 because isset($_POST["csgo"]) is false.

If the checkbox is checked and then the form is submitted, $csgoac will be 1.

So the question becomes: What is the result of mysqli_query($db, $sql);?

Are you getting/checking all available feedback? If display_errors is Off in php.ini, there will not be feedback in the browser, but perhaps an error is in the php errorlog. (For instance, in the snippet, $db is not defined, so mysqli_query($db, $sql); fails with Undefined variable: db.).

If the UPDATE is not successful, mysqli_query($db, $sql); will return FALSE and $db->error should tell you what error was encountered.

You could also use mysqli_stmt_affected_rows for additional feedback.

Perhaps add some feedback/error checking to get as much information as possible so you can know what is really happening.