Search code examples
phparraysdatabasemultiple-columnsdropdown

PHP multiple arraw selected from database


Hello please can anyone give idea for this?
I want data will selected when it match with their id but when i try this some data will not selected just display only how can I make it selected by their ID?
In this array it work:

[0] => 1 [1] => 2 [2] => 3

In this array it won't work:

[0] => 20 [1] => 21 [2] => 22 [3] => 23 [4] => 24 
$stat = $dbh->prepare("SELECT * FROM department");
$stat2 = $dbh->prepare("SELECT * FROM docprivacy WHERE doc_id = $id ORDER BY dep_id");   

$stat2->execute();

$array = array();

while ($row3 = $stat2->fetch()) {
    extract($row3);
 array_push($array, $row3['dep_id'] )    ; 
}

$stat->execute();
$i = 0 ;

while($row = $stat->fetch()){
    extract($row);
    while ( $i < count($array)) {
        # code...

     if ($row['d_id'] == $array[$i]){
       echo "<option value = '{$d_id}' selected>".$row['department']."</option>";
      }else{
        echo "<option value = '{$d_id}'>".$row['department']."</option>";
    }

    $i++;
  }
}

Solution

  • if (in_array($row['d_id'], $array ))
      {
         echo "<option value = '{$row['d_id']}' selected>".$row['department']."</option>";
      }
    else
      {
        echo "<option value = '{$row['d_id']}'>".$row['department']."</option>";
      }