Darkside
Darkside

Reputation: 11

in_array not working from fetch_array created array

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

Upvotes: 0

Views: 241

Answers (1)

kero
kero

Reputation: 10638

$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

Upvotes: 2

Related Questions