0

How do I write php code to check if checkbox is checked or not ? if checkbox is selected then YES value stored in the database, and if checkbox is not selected, then NO valued stored in the database. How to do that? I know how to connect database etc. thanks

1
  • 1
    Please take a look at the related questions on the right of this one. Commented Feb 24, 2011 at 8:31

4 Answers 4

6
<input type="checkbox" name="cb1" value="YES" />

$cb1 = ($_POST['cb1'] == 'YES')?'YES':'NO';

If the checkbox is not clicked the value will be null i.e. the variable $_POST['cb1'] will not be set.

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

1 Comment

this will trigger E_NOTICE. You should try using isset($_POST['cb1']) instead of $_POST['cb1'] == 'YES'
5

If a checkbox isn't checked, it won't be in the HTTP body of your post, so you'll have to check if it's set. You can obviously do that with a simple if statement, or with the ternary operator:

<input type="checkbox" name="foo" value="yes" />

Then on the PHP side of things:

<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
    if( isset( $_POST['foo'] ) ) {
         $foo = 'YES';
    }
    else {
         $foo = 'NO';
    }

    // shorter though:
    $foo = isset( $_POST['foo'] ) ? $_POST['foo'] : 'no';

    echo $foo;
}
?>

Comments

0

See http://www.html-form-guide.com/php-form/php-form-checkbox.html

Comments

0

I'm assuming that you know how POST and forms work in HTML.

All you have to do is put a check-box control inside a form and give it a "name" attribute.

Then when the form posts back to the server you can check $_POST["YourNameHere"] and get the value eg:

$val = $_POST["key"];

Comments

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.