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
-
1Please take a look at the related questions on the right of this one.Gumbo– Gumbo2011-02-24 08:31:07 +00:00Commented Feb 24, 2011 at 8:31
Add a comment
|
4 Answers
<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.
1 Comment
Carlos Campderrós
this will trigger E_NOTICE. You should try using
isset($_POST['cb1']) instead of $_POST['cb1'] == 'YES'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;
}
?>