I'm new to html so i'm unsure where im going wrong but i have the following code (i'm creating a form and adding values to the database when the user presses submit).
a checkbox nested in a form -
<label for="choice1">Windows 7</label>
<input type="checkbox" name="choice1"/>
and when the user presses 'add button' i'm trying to get the value and store it in a variable but it cannot find 'ch开发者_StackOverflow社区oice1'.
$choice1=$_POST['choice1'];
but i get "Undefined index: choice1". Why is this?
If the checkbox is checked, the browser sends its value with other variables.
If it's not checked, it's not sent.
Do this:
$choice1 = isset($_POST['choice1']) ? $_POST['choice1'] : 0;
There are two things that can go wrong here:
- If the form doesn't have the attribute
method
set topost
, the data is passed in the URL (you can check if that is the case). In that case, the values are in $_GET rather than $_POST. - Checkboxes that are not checked don't pass a value. If the checkbox is checked, it passes
on
(or another value, if you override it) but if you don't, you don't get the value, so you cannot read it in PHP. You can check if the value exists usingarray_key_exists('choice1', $_POST)
. If it doesn't you know the checkbox isn't checked.
- Make sure your form uses POST (not GET), otherwise
$_POST
will be empty. For example:
<form action="foo" method="post">
- Do a
print_r($_POST)
to see if there's anything inside$_POST
. - As Matt says in the comments, make sure your have
<input type="submit">
to actually send your form.
If you do something like this should work:
<FORM action="your next page" method="post">
.....
<label for="choice1">Windows 7</label>
<input type="checkbox" name="choice1"/>
.....
<input type="submit"/>
</FORM>
Check if your code is the same... Otherwhise post more code to give a look at...
精彩评论