Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
share|improve this question
 
$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 '13 at 11:36
add comment

1 Answer

up vote 2 down vote accepted
$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

share|improve this answer
 
Thats been wrecking my head for hours , thanks you so much –  Darkside Dec 4 '13 at 11:44
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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