复选框值带有单个值

时间:2014-12-31 13:03:22

标签: php mysql checkbox

我的代码正在运行,但如果我从表单中选择了值,然后只选择了单个增值数据库,则会出现问题。哪里出错了。

<?php
$con = mysqli_connect('localhost', 'root', '12345', 'fruit');
if ($_SERVER['REQUEST_METHOD'] != 'POST' && !isset($_POST['submit'])) {
    echo '<form action="" method="post">
    <input type="checkbox" name="fruits[]" value="Apple" />APPLE<br />
            <input type="checkbox" name="fruits[]" value = "Lemon" />LEMON<br />
            <input type="submit" name="submit" value="POST">
</form>';
}elseif ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit'])){
    $fruit = $_POST['fruits'];
    foreach ($fruit as $fruits){
        $fruits = mysqli_real_escape_string($con, strip_tags($fruits));
    }
    $sql_add = mysqli_query($con, "INSERT INTO fruit (name) VALUES ('$fruits')");
    if (mysqli_affected_rows($con) == 1) {
        echo "Ok not problem.";
    }else {
        echo "There are some problem. Please submit your choice again.";
    }
}

1 个答案:

答案 0 :(得分:1)

在插入语句

之后结束for循环
foreach ($fruit as $fruits){
    $fruits = mysqli_real_escape_string($con, strip_tags($fruits));
    $sql_add = mysqli_query($con, "INSERT INTO fruit (name) VALUES ('$fruits')");
}