使用 php 获取多个复选框名称/id [英] getting multiple checkboxes names/id's with php

查看:25
本文介绍了使用 php 获取多个复选框名称/id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 PHP 在提交时获取多个选定复选框的名称或 ID?以下是示例表格.谢谢.

How can i get the names or id's of the multiple selected checkboxes on submit, using the PHP? Following is example form. Thanks.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
   <input type="checkbox" name="orange" id="orange">
   <input type="checkbox" name="apple" id="apple">
   <input type="checkbox" name="sky" id="sky">
   <input type="checkbox" name="sea" id="sea">
   <br>
   <br>
   <input type="submit" name="Submit" value="Submit">
</form>

推荐答案

只有在选择复选框时,才会从表单提交复选框.更重要的是,重要的是名称属性,而不是 ID.

Checkbox values are submitted from a form only if the checkbox is selected. What's more, it's the name attribute that counts, not the ID.

PHP 中有几种处理复选框的方法:

There are several ways of handling checkboxes in PHP:

  1. 为所有复选框提供相同的名称,后跟一对方括号,因此整个集合被视为一个数组.在这种情况下,为每个复选框指定一个值.
  2. 为每个复选框指定不同的名称和值.
  3. 为每个复选框指定不同的名称,但没有值.

在每种情况下,您都需要检查 $_POST 数组中是否存在复选框名称.

In each case, you need to check for the existence of the checkbox name in the $_POST array.

例如:

<input type="checkbox" name="color[]" id="orange" value="orange">
<input type="checkbox" name="color[]" id="apple" value="apple">

要获取这些复选框的值:

To get the values for these checkboxes:

if (isset($_POST['color'])) {
    $colors = $_POST['color'];
    // $colors is an array of selected values
}

但是,如果每个复选框都有不同的名称和明确的值,如下所示:

However, if each checkbox has a different name and an explicit value like this:

<input type="checkbox" name="orange" id="orange" value="orange">
<input type="checkbox" name="apple" id="apple" value="apple">

你仍然需要使用isset():

You still need to use isset():

if (isset($_POST['orange'])) {
    // orange has been set and its value is "orange"
}

如果不设置值,默认值为"on",但除非被选中,否则不会出现在$_POST数组中,所以还是需要使用isset().

If you don't set a value, the default value is "on", but it won't be in the $_POST array unless it has been selected, so you still need to use isset().

这篇关于使用 php 获取多个复选框名称/id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆