如何处理 PHP 表单中的多个复选框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6881039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:32:25  来源:igfitidea点击:

How to handle multiple checkboxes in a PHP form?

phphtml

提问by Jake

I have multiple checkboxes on my form:

我的表单上有多个复选框:

<input type="checkbox" name="animal" value="Cat" />
<input type="checkbox" name="animal" value="Dog" />
<input type="checkbox" name="animal" value="Bear" />

If I check all three and hit submit, with the following code in the PHP script:

如果我检查所有三个并点击提交,在 PHP 脚本中使用以下代码:

if(isset($_POST['submit']) {
   echo $_POST['animal'];
}

I get "Bear", i.e. the last chosen checkbox value even though I picked all three. How to get all 3?

我得到“熊”,即最后选择的复选框值,即使我选择了所有三个。如何获得全部3个?

回答by fatnjazzy

See the changes I have made in the name:

查看我对名称所做的更改:

<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />

you have to set it up as array.

您必须将其设置为数组。

print_r($_POST['animal']);

回答by Andrew Winter

<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />

If I check all three and hit submit, with the following code in the PHP script:

如果我检查所有三个并点击提交,在 PHP 脚本中使用以下代码:

if(isset($_POST['animal'])){
    foreach($_POST['animal'] as $animal){
        echo $animal;
    }
}

回答by Jonathan Fingland

use square brackets following the field name

在字段名称后使用方括号

<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />

On the PHP side, you can treat it like any other array.

在 PHP 方面,您可以像对待任何其他数组一样对待它。