我是PHP的新手。
现在我遇到有关复选框值的问题。我从这些页面中搜索了他们的解决方案对我的案例不起作用的答案。
Trying to set default checkbox value if not checked
Post the checkboxes that are unchecked(我不知道将JS放在哪里)
how do I get all checkbox variables even if not checked from HTML to PHP?
到目前为止,这些是我的代码......
<form method="POST" action="testinsertskill.php">
<br><br>Required Skills :
**//skip the sql parts because there is no problem from calling the data from database**
<?php
while ($row2 = mysql_fetch_array($result2, MYSQL_ASSOC)) {
?>
<input type="hidden" id="hidden_skills" name="skills[]" value="0" />
<br /><input type="checkbox" id="skills" name="skills[]" value="1" /><?php echo $row2['Skill_Name']; ?><br />
<?php
$count++;
}
?>
<input type="hidden" name="counter" value="<?=$count?>" />
<input type="submit" name="submit" value="Confirm">
</form>
这是testinsertskill.php页面
<?php session_start();
$servername = "localhost";
$username = "root";
$password = "rootroot";
$dbname = "onlinerecruitment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$skill = $_POST['skills'];
$count = $_POST['counter'];
for($i = 0; $i < $count; $i++){
$sql = "INSERT INTO applicant_skill VALUES('".$skill[$i]."')";
$resultt = "";
if ($conn->query($sql) == TRUE) {
$resultt = "FINISH";
} else {
$resultt = "ERROR";
}
}
$conn->close();
?>
假设有5种技能可供选择,我选择第2和第4。
预期结果应该是(0,1,0,1,0)在数据库中,但由于隐藏输入,结果是(0,0,1,0,0)。现在我不知道该怎么办,因为我提到的那些链接无法解决我的问题,或者我不知道我要把它放在哪里。请帮忙。
答案 0 :(得分:1)
我假设您还有一些Skill_Id,然后代码看起来像这样
<form method="POST" action="testinsertskill.php">
<br><br>Required Skills :
**//skip the sql parts because there is no problem from calling the data from database**
<?php
while ($row2 = mysql_fetch_array($result2, MYSQL_ASSOC)) {
?>
<input type="hidden" name="skills[<?= $row2['Skill_Id'] ?>]" value="0" />
<br /><input type="checkbox" name="skills[<?= $row2['Skill_Id'] ?>]" value="1" /><?= $row2['Skill_Name'] ?><br />
<?php
}
?>
<input type="submit" name="submit" value="Confirm">
</form>
然后插入代码:
//....
foreach($_POST['skills'] as $skillId => $skill){
$sql = "INSERT INTO applicant_skill VALUES('".$skill."')";
$resultt = "";
if ($conn->query($sql) == TRUE) {
$resultt = "FINISH";
} else {
$resultt = "ERROR";
}
}