vendredi 20 décembre 2019

Loop through checkboxes and display checked if 'ID'=='ID'

I'm fairly new to PHP and need a bit of guidance. I have a page called createemployee.php that uses a for loop to display checkboxes used to define an employees skillset, the following code works:

<?php for($i = 0; $i < count($skills); $i++):?>
    <span class="description">
         <input  id="customCheck1" type="checkbox" name="skills[]" value="<?=$skills[$i]['skill_id'];?>">
         <label class=" badge badge-warning" for="customCheck1"><?=$skills[$i]["skill_name"]?></label>
    </span>
<?php endfor;?>

I'm trying to create a page for editemployee.php in which the details of a specific employee is loaded and editable by the user. I would like to display checked values if the checkbox was checked.

I am using a linking table to allow one employee to have multiple skills, like so:

CREATE TABLE emp_skill (
emp_skill_id INT PRIMARY KEY UNSIGNED AUTO_INCREMENT,
emp_id INT UNSIGNED,
skill_id INT UNSIGNED,
FOREIGN KEY emp_id REFERENCES employee(`emp_id`),
FOREIGN KEY skill_id REFERENCES skill(`skill_id`)
);

If I nest for loops like so (this is wrong, but testing=learning and it gave me an output similar to what I'm wanting), the output is printed with the correct checkboxes selected, but the data taken from skills is duplicated each time it is equal to emp_skill (due to nesting for loops).

 <?php for($j = 0; $j < count($emp_skill); $j++):?>
  <?php for($i = 0; $i < count($skills); $i++):?>
      <span class="description">
          <input  id="customCheck1" type="checkbox" name="skills[]" value="<?=$skills[$i]['skill_id'];?>" 
          <?php if ($skills[$i]["skill_id"]==$emp_skill[$j]['skill_id']) echo 'checked="checked"';?>>
          <label class=" badge badge-warning" for="customCheck1"><?=$skills[$i]["skill_name"]?></label>
     </span>
 <?php endfor;?>
<?php endfor;?>

I am looking for advice on how I can output checked values if $skill.skill_id is matching a row within the $emp_skill.skill_id without duplicating the output of $skill on the webpage?

I assume I will need to use a loop of some kind (maybe foreach or while, opposed to for), but as I said - I'm fairly new to PHP and I've been stuck on this part for a few hours! Any guidance would be appreciated. TIA




Aucun commentaire:

Enregistrer un commentaire