【问题标题】:Retrieve selected checkboxes with $_POST使用 $_POST 检索选中的复选框
【发布时间】:2020-01-29 19:22:26
【问题描述】:

我的表单中有以下输入字段:

    <label class="addFileSectionSelectArea">
        <span class="addFileSectionSelectAreaText">לבנון</span>
        <input type="checkbox" name="add_file[areas]" value="lebanon">
        <div>
            <svg viewBox="0 0 44 44">
                <path d="M14,24 L21,31 L39.7428882,11.5937758 C35.2809627,6.53125861 30.0333333,4 24,4 C12.95,4 4,12.95 4,24 C4,35.05 12.95,44 24,44 C35.05,44 44,35.05 44,24 C44,19.3 42.5809627,15.1645919 39.7428882,11.5937758" transform="translate(-2.000000, -2.000000)"></path>
            </svg>
        </div>
    </label>
    <label class="addFileSectionSelectArea">
        <span class="addFileSectionSelectAreaText">סוריה</span>
        <input type="checkbox" name="add_file[areas]" value="syria">
        <div>
            <svg viewBox="0 0 44 44">
                <path d="M14,24 L21,31 L39.7428882,11.5937758 C35.2809627,6.53125861 30.0333333,4 24,4 C12.95,4 4,12.95 4,24 C4,35.05 12.95,44 24,44 C35.05,44 44,35.05 44,24 C44,19.3 42.5809627,15.1645919 39.7428882,11.5937758" transform="translate(-2.000000, -2.000000)"></path>
            </svg>
        </div>
    </label>

PHP,我尝试检索(提交后)选中的复选框:

        $debug = $_POST['add_file']['areas'];

当我这样做时:var_dump($debug) 它总是返回代表 last 选中复选框的值的字符串值(但我希望它返回所有选中复选框的数组)。

因此,例如,如果我同时选中 [value='syria'][value='lebanon'] 复选框,那么我只会在 var_dump 中得到一个值为“syria”的字符串(因为 syria 输入在 html 中的 lebanon 输入之后)。 这是为什么呢?

【问题讨论】:

  • 执行name="add_file[areas][]" 使其成为一个值数组。尽管除非有原因,否则我会选择name="add_file_areas[]" 并在$_POST['add_file_areas'] 中访问它。

标签: php html


【解决方案1】:

您需要以空数组语法 [] 结束名称,以便为复选框组附加另一个元素,因此:

 <input type="checkbox" name="add_file[]" value="syria">

或者如果 areas 数组部分由于某种原因很重要:

 <input type="checkbox" name="add_file[areas][]" value="syria">

这里有一个很好的指导:Handling checkbox in a PHP form processor

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多