0

I am having difficulties with an array. I have a table in my DB with a many to many relationship, where by an employee can have multiple skills and a skill can be associated with multiple employees. I am trying to setup a form where a user can use checkboxes to show which skills an employee has.

I am currently stuck on displaying the check boxes with the boxed checked if a value is returned from the DB. I am running a select statement to get the data and then saving this to an array (print_r shows the correct data is there) And then i am trying to us in_array to determine if the checkbox should be checked or not, but nothing happens. Can someone see what I am doing wrong ? Thanks (set statically below to employee 11, this has 3 results)

<?php   
require_once('db_connect.php');

    $array = array();
    $qry = "SELECT skill_id FROM skillsets WHERE emp_id = 11";

    $stmt = $mysqli->prepare($qry);

    $stmt->execute();
    $result = $stmt->get_result();

    while($row = $result->fetch_array(MYSQLI_NUM))
    {
    $array[] = $row;
    }

?>
                <input type="checkbox" name="chk1[]" value="1" <?php if(in_array("1", $array)){echo 'checked="checked"';}?> >skill1
                <input type="checkbox" name="chk1[]" value="3" <?php if(in_array("3", $array)){echo 'checked="checked"';}?> >skill2
                <input type="checkbox" name="chk1[]" value="5" <?php if(in_array("5", $array)){echo 'checked="checked"';}?> >skill3
                <input type="checkbox" name="chk1[]" value="2" <?php if(in_array("2", $array)){echo 'checked="checked"';}?> >skill4
                <input type="checkbox" name="chk1[]" value="6" <?php if(in_array("6", $array)){echo 'checked="checked"';}?> >skill5
                <input type="checkbox" name="chk1[]" value="4" <?php if(in_array("4", $array)){echo 'checked="checked"';}?> >skill6
1
  • $row is already an array by putting it in $array[] you're creating a multidimentional array there's no need just do in_array("1",$row);
    – Dave
    Dec 4, 2013 at 11:36

1 Answer 1

2
$array[] = $row;

This saves the array $row as new element of $array. The structure would be like this

Array(
    Array(0),
    Array(1),
    Array(2),
    ...
)

Instead, change your code to the following:

while($row = $result->fetch_array(MYSQLI_NUM)) {
    $array[] = $row[0];
}

this will give you the structure

Array(
    0,
    1,
    2,
    ...
)

and the in_array should work just fine

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.