开发者

Undefined index html

开发者 https://www.devze.com 2023-04-04 21:14 出处:网络
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).

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:

  1. If the form doesn't have the attribute method set to post, 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.
  2. 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 using array_key_exists('choice1', $_POST). If it doesn't you know the checkbox isn't checked.


  1. Make sure your form uses POST (not GET), otherwise $_POST will be empty. For example:
    <form action="foo" method="post">
  2. Do a print_r($_POST) to see if there's anything inside $_POST.
  3. 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...

0

精彩评论

暂无评论...
验证码 换一张
取 消