【问题标题】:Get all values from checkboxes? [duplicate]从复选框中获取所有值? [复制]
【发布时间】:2011-07-08 03:56:32
【问题描述】:

有没有一种简单的方法来获取多个复选框的值并将它们存储在数据库中?

<?php
if(isset($_POST['go'])){
   $fruit = $_POST['fruit'].",";
   echo $fruit;
   // if you selected apple and grapefruit it would display apple,grapefruit
}
?>
<form method="post">
Select your favorite fruit:<br />
<input type="checkbox" name="fruit" value="apple" id="apple" /><label for="apple">Apple</label><br />
<input type="checkbox" name="fruit" value="pinapple" id="pinapple" /><label for="pinapple">Pinapple</label><br />
<input type="checkbox" name="fruit" value="grapefruit" id="grapefruit" /><label for="grapefruit">Grapefruit</label><br />
<input type="submit" name="go" />
</form>

【问题讨论】:

  • name="fruit"更改为name="fruit[]",删除$fruit = $_POST...,将echo $fruit;更改为echo implode(',',$_POST['fruit'])
  • 将复选框命名为“name=fruit[]”,以便将它们发送到数组

标签: php html mysql checkbox


【解决方案1】:

如果给复选框赋予相同的名称,以 [] 结尾,则值将作为数组返回。

<input type="checkbox" name="fruit[]" value="apple" />
<input type="checkbox" name="fruit[]" value="grapefruit" />

然后在 PHP ...

if( isset($_POST['fruit']) && is_array($_POST['fruit']) ) {
    foreach($_POST['fruit'] as $fruit) {
        // eg. "I have a grapefruit!"
        echo "I have a {$fruit}!";
        // -- insert into database call might go here
    }

    // eg. "apple, grapefruit"
    $fruitList = implode(', ', $_POST['fruit']);
    // -- insert into database call (for fruitList) might go here.
}

PS。请原谅这个明显的错误,这个例子可能会喊“我有一个苹果”......我不认为让这个例子足够聪明,以确定何时使用“a”,何时使用“an”:P

【讨论】:

    【解决方案2】:

    这样命名你的输入:

    <input type="checkbox" name="fruit[]" value="apple" id="apple" /><label for="apple">Apple</label><br />
    <input type="checkbox" name="fruit[]" value="pinapple" id="pinapple" /><label for="pinapple">Pinapple</label><br />
    

    然后在 $_POST['fruit'] 上迭代:

    if(isset($_POST['fruit']) && !empty($_POST['fruit']))   
        foreach($_POST['fruit'] as $fruit) echo $fruit;
    

    【讨论】:

      【解决方案3】:

      添加到其他解决方案...

      implode 和 explode 可用于 PHP 将您的fruit[] 数组转换为逗号分隔的列表。

      $valueToStoreInDB = implode(",",$_POST['fruit']);
      $fruitAsAnArrayAgain[] = explode(",",$dbvalue);
      

      一旦有了逗号分隔列表,在 MySQL 中表示复选框的良好数据类型将是 SET,您可以将逗号分隔列表直接粘贴到插入语句中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-01
        • 2016-04-14
        • 2019-06-19
        相关资源
        最近更新 更多