如何使用foreach插入多个值

时间:2014-12-13 08:22:26

标签: php mysql

使用foreach添加复选框值。复选框名称相同.. enter image description here

我试过这个

<?php
// checkbox name is check[]
$check = $_POST['check']; 
foreach($check as $checks => $checked)
{
 $value = $checked;
 $sql = mysql_query("INSERT INTO `db` (`db_column`) VALUES ('".$value."')"); 
}
?>

2 个答案:

答案 0 :(得分:4)

        <form name="form1" action="count.php" method="POST">
         <input type="checkbox" name="check[]" value="your value">
         <input type="checkbox" name="check[]" value="your value1">
         <input type="checkbox" name="check[]" value="your value2">
         <button type="submit" name="btn">Ok</button>
         </form>
         <?php
         if(isset($_POST['btn'])){
            $check = $_POST['check'];
            print_r($check);foreach($check as $checks => $checked){
                $value = $checked;

             $sql = mysql_query("INSERT INTO `db` (`db_column`) VALUES ('".$value."')"); 
            }
         }
         ?>

答案 1 :(得分:0)

PHP支持多维请求参数。但是您需要更改表单结构。我给你一个基本的例子:

<?php
if(isset($_POST) && isset($_POST['example_checkbox'])) {
    foreach($_POST['example_checkbox'] as $key => $value) {
        echo "The balue of $key is $value<br />";
    }
    exit;
}
?>
<html>
    <head>
        <title>Example</title>
    </head>
    <body>
        <form method="post">
            <input type="checkbox" name="example_checkbox[checkbox_1]" value="1" />1<br />
            <input type="checkbox" name="example_checkbox[checkbox_2]" value="2" />2<br />
            <input type="checkbox" name="example_checkbox[checkbox_3]" value="3" />3<br />
            <input type="checkbox" name="example_checkbox[checkbox_4]" value="4" />4<br />
            <input type="checkbox" name="example_checkbox[checkbox_5]" value="5" />5<br />
            <input type="checkbox" name="example_checkbox[checkbox_6]" value="6" />6<br />
            <input type="submit" />
        </form>
    </body>
</html>