我正在学习PHP,并且在将复选框值插入数据库中时遇到问题,
请告诉我有什么问题。感谢U
如何修复此代码以存储所有检查的值?
<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>
答案 0 :(得分:0)
您的表单提交按钮配置不正确,应该为<button type="submit" name="submit">Submit</button>
。另外,由于未通过PDO
完成SQL查询,因此未执行SQL查询。
这是一个可能的解决方案:
...
<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>
...