【问题标题】:How to insert multiple check-box values inside database when one or more will be left unchecked?当一个或多个未选中时,如何在数据库中插入多个复选框值?
【发布时间】:2012-07-24 18:49:02
【问题描述】:

我有一个包含 5 个复选框的表单。用户可以选择这些复选框中的一个或多个。用户可以选择 2 并且不选中 3 或选择 4 并且不选中 1 等等,在这种情况下,我该如何编写将表单数据插入数据库的 php/mysql 代码。只需一个选择就很容易了,我会这样做:

$checkbox_value = $_POST['i_agree'];

mysql_query("INSERT INTO terms (user, pass, conditions) VALUES ('$user','$pass','$checkbox_value')");

但是当有多个复选框选项并且只有一个或多个会被选中时,我该怎么写呢?

我想将它们全部插入一个名为“标签”的列中,用逗号分隔。

【问题讨论】:

    标签: php mysql forms


    【解决方案1】:
    <?php 
    <body>
    <form action="checkbox.php" method="post">
    <input type="checkbox" name="checkbox[]" value="a">
    <input type="checkbox" name="checkbox[]" value="b">
    <input type="checkbox" name="checkbox[]" value="c">
    <input type="checkbox" name="checkbox[]" value="d">
    <br>
    <br>
    <input type="submit" name="Submit" value="Submit">
    </form>
    <?
    
    /* and in your checkbox.php you do this: */
    
    if(isset($_POST['Submit']))
    {
    for ($i=0; $i<count($_POST['checkbox']);$i++) {
     $check_val .= $_POST['checkbox'][$i];
     $check_val .=","; 
    }
    }
    ?>
    

    现在 $check_val 将拥有所有复选框值,现在您可以将其放入数据库中。

    【讨论】:

    • 这样多加逗号,最好用implode:$check_val = implode(',', $_POST['checkbox']);
    【解决方案2】:
    <html>
    <body>
    <form action="" method="post">
    <table>
    
    <tr>
       <td>Football</td><td><input name="region[]" type="checkbox" value="football">
       </td>
    </tr>
    <tr>
       <td>Handball</td><td><input name="region[]" type="checkbox" value="handball">
       </td>
    </tr>
    <tr>
       <td>Baseball</td><td><input name="region[]" type="checkbox" value="handball">
       </td>
    </tr>
    <tr><td><input type="submit" value="Submit"></td></tr>
    </table>
    </form>
    </body>
    </html>
    
    <?php
    include("connection.php");
        foreach($_POST['region'] as $value)
    {?
    <?php $sql = mysql_query("INSERT INTO sports SET region = '" . implode(',', $_POST['region']) . "'"); 
     }
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-28
      • 2011-08-12
      • 1970-01-01
      • 2020-04-22
      • 2015-07-27
      • 2018-05-28
      • 1970-01-01
      • 2019-08-28
      相关资源
      最近更新 更多