3

I had a look at checkbox value 0 or 1 but am a little confused.

In the DB, columns hosting, complete_setup, and legal_compliant are either 1 or 0, if the user checks the checkbox, it updates it to 1:

<div class="form-group <?php echo (!empty($complete_setup_err)) ? 'has-error' : ''; ?>">
    <label>Complete Setup</label>
    <input type="checkbox" class="form-control" name="complete_setup" value="1" />
    <span class="help-block"><?php echo $complete_setup_err; ?></span>
</div>

But what I would like, is if in the db it is already 1 the the checkbox to already be checked and if it is unchecked it to update the DB to 0. How do I make it return the value 0?

Thank you!

1 Answer 1

2

The issue is that not checked checkboxes are not at all sent to the server. That means that if check, then the variable is part of the posted values, if not checked it is not sent. You could modify that behavior on the client side, but it is much easier to simply evaluate the given information on the receiving server side:

You can evaluate whether the variable is present in the posted variables:

$isChecked = (isset($_POST['complete_setup']) && $_POST['complete_setup'] == 1) ? 1 : 0;

To control if the checkbox is already checked when you hand out the form requires to actively mark the checkbox as checked:

<?php $isChecked = ($row['complete_setup'] == 1) ? 'checked' : ''; ?>
<input type="checkbox" class="form-control" name="complete_setup" value="1" checked="<?php echo $isChecked ?>"/>

This assumes that you read the content of the database table into some array $row which should then contain the value 1 in the array element complete_setup.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi @arkascha - they are update via the following trim($_POST['complete_setup']), so how would I include the $isChecked line into that? Thanks!
There is no sense in calling the trim() function on such a value. Just replace trim($_POST['complete_setup']) with $isChecked is probably fine. Or directly with the term assigned to $isChecked, obviously. But I can't say for sure without you posting your actual code.
Just a note: $isChecked = !empty($_POST['complete_setup']) is a shorter way to test for checked checkboxes in most cases.
@Jeto Sure, possible, this assumes that all values of the variable signal a checked checkbox, though. That is not really clear from the OP's description though. So it depends on the actual situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.