Undefined index html

霸气de小男生 提交于 2020-01-05 04:42:54

问题


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 'choice1'.

$choice1=$_POST['choice1'];

but i get "Undefined index: choice1". Why is this?


回答1:


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;



回答2:


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.



回答3:


  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.



回答4:


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...



来源:https://stackoverflow.com/questions/7429820/undefined-index-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!