gznero gznero - 6 months ago 11
PHP Question

(PHP) How to set default value to unchecked checkbox

I'm new to PHP.

Now I face this problem about the checkbox value. I search the answer from these pages which their solutions are not working to my case.

Trying to set default checkbox value if not checked

Post the checkboxes that are unchecked (I don't know where to put the JS with)

how do I get all checkbox variables even if not checked from HTML to PHP?

These are my codes so far...

<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>


And this is testinsertskill.php page

<?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();

?>


Assume that there are 5 skills to select and I select 2nd and 4th.

Expected result should be (0,1,0,1,0) in database but it turns out (0,0,1,0,0) because of hidden input. Now I don't know what to do because those links I referred cannot solved my problem or I don't know where I have to put it. Please help.

Answer

I assume you have also some Skill_Id then code could look like this

<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>

And then insert code:

//....
foreach($_POST['skills'] as $skillId => $skill){

    $sql = "INSERT INTO applicant_skill VALUES('".$skill."')"; 

        $resultt = "";

        if ($conn->query($sql) == TRUE) {
           $resultt = "FINISH";
        } else {
           $resultt = "ERROR";
        }

}
Comments