php - 在 mysql 数据库中插入复选框值

标签 php html mysql

我正在学习 PHP,但在将复选框值插入我的数据库时遇到了问题, 请告诉我哪里出了问题。谢谢你

如何修复此代码以存储所有选中的值?

<html>
<body>
    <form action="submit.php" method="post" enctype="multipart/form-data">
        <input type="checkbox" name="ch[]" id="ch" value="JAVA">JAVA <br>
        <input type="checkbox" name="ch[]" id="ch" value="C++">C++ <br>
        <input type="checkbox" name="ch[]" id="ch" value="JS">JS <br>
        <input type="checkbox" name="ch[]" id="ch" value="C">C <br>
        <input type="button" value="submit" name="submit">
    </form>
    <?php
try {
            $bdd = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');
        } catch (Exception $th) {
            die('Error'.$th->getMessage());
        }
        if(isset($_POST["submit"])){
            $check =implode(',',$_POST['ch']);
            $qry = $bdd->prepare("INSERT INTO test inputC VALUES ('$check')");    
            $res=mysql_query($qry);
            if($res){
                echo "insert success";
            }else{
                echo "error in inserting";
                }
            }
        ?>
</body>
</html>

最佳答案

您的表单提交按钮配置不正确,应该是<button type="submit" name="submit">Submit</button> .此外,SQL 查询未被执行,因为这不是 PDO 的处理方式。 .

这是一个可能的解决方案:

...
<body>
    <form method="post" action="submit.php" enctype="multipart/form-data">
        <input type="checkbox" name="ch[]" id="ch" value="JAVA">JAVA <br>
        <input type="checkbox" name="ch[]" id="ch" value="C++">C++ <br>
        <input type="checkbox" name="ch[]" id="ch" value="JS">JS <br>
        <input type="checkbox" name="ch[]" id="ch" value="C">C <br>
        <button type="submit" name="submit">Submit</button>
    </form>
    <?php
    try {
        $bdd = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');
        $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (Exception $th) {
        die('Error'.$th->getMessage());
    }

    if(isset($_POST["submit"])) {
        try {
            $check = implode(',',$_POST['ch']);
            $stmt = $bdd->prepare("INSERT INTO test (inputC) VALUES (?)");  

            $stmt->execute([$check]);

            if ($bdd->lastInsertId() != -1) {
                echo "insert success";
            } else {
                echo "error in inserting";
            }
        } catch(PDOException $e) {
            die("Error: ".$e->getMessage());
        }
    }
}
?>
</body>
...

关于php - 在 mysql 数据库中插入复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54835748/

相关文章:

html - 在 HTML 页面上覆盖 float 的全宽侧边栏

html - 在父 DIV 中垂直居中 CSS::after Content,带 float

mysql - 为什么银行或金融公司在其 "Core"系统中更喜欢 Oracle 而不是其他 RDBMS?

php - 关于行数的 mysql_result 的语法问题

php - 将对象从 Controller 传递到 View

php - 如何在滚动页面时将值加载到页面

php - 删除数据库表中的特定行并生成html表

javascript - 如何使用 HTML/CSS/JavaScript 在一个元素上垂直对齐列表?

mysql - 在安装过程中我无法创建用户以及其他安装问题

php - CakePHP 奇怪的 saveAll 问题。返回true,但数据库中没有任何内容