-1

I have code table like this.

code       
00
01
02
03

I'm adding this codes as array from dropdown list to assigned_code column in the user table.

assigned_code
00,02,03

When I want to edit the codes assigned to the user, I need to add selected attribute which codes are assigned previously in dropdown list. I'm stuck at this point. Can anyone show me the how to do this?

<?php
  $assigned_code = array();

  $sql   = "select assigned_code from user where ID=1";
  $rq    = mysqli_query($conn, $sql);
  $count = mysqli_num_rows($rq);
  if ($count>0) {
    while ($row = mysqli_fetch_array($rq)) {
      $assigned_code=$row["$assigned_code"];
    }
  }
?>

<select name="u_codes[]" id="u_codes" class="selectpicker" multiple="multiple">

<?php
  $sql = "select code,desc from codes";
  $rq  = mysqli_query($conn, $sql);
  while ($row = mysqli_fetch_array($rq)) {
    $code     = $row["code"];
    $codeDesc = $row["desc"];
    if ($assigned_code == $code) {
      echo '<option value="'.$code.'" selected="selected">'.$codeDesc.'</option>';
    } else {
      echo '<option value="'.$code.'">'.$codeDesc.'</option>';
    }
  }
?>

</select>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • `$assigned_code=$row["$assigned_code"];` you probably want to push items to the array using `$assigned_code[]=$row["$assigned_code"];` – berend Nov 13 '20 at 09:51
  • You will of course have to split the value `00,02,03` into the individual codes again, before it makes sense to try and _compare_ it to a single code. But actually, you should not store data like this in the first place - the keyword you should go read up on here, is _database normalization_. – CBroe Nov 13 '20 at 09:57
  • Does this answer your question? [How can I check if an array contains a specific value in php?](https://stackoverflow.com/questions/8881676/how-can-i-check-if-an-array-contains-a-specific-value-in-php) – SamMorrowDrums Nov 13 '20 at 16:45

2 Answers2

0

try using array_push to items

array_push($assigned_code,$row["$assigned_code"]);

because every time you use $assigned_code=$row["$assigned_code"]; you erase the existing value inside $assigned_code

and debug it with var_dump() it will give you a clear information about the data and it's type.

achraf
  • 5
  • 2
0
$assigned_code = array();   
$assigned_code=$row["$assigned_code"];

$expArr = explode(',',$assigned_code);  

if (in_array($code,$expArr)) {
    echo '<option value="'.$code.'" selected="selected">'.$codeDesc.'</option>';
} else { 
    echo '<option value="'.$code.'">'.$codeDesc.'</option>';
}

in_array perfectly worked for me.