我是 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)。现在我不知道该怎么办,因为我提到的那些链接无法解决我的问题,或者我不知道我必须把它放在哪里。请帮忙。
最佳答案
我假设您还有一些 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";
}
}
关于javascript - (PHP) 如何为未选中的复选框设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37372354/