Rosy
Rosy

Reputation: 37

Populating drop down list in the PHP variable

    while ($row = mysqli_fetch_array($result)){
      $move = '
        <select type = text name="mover">
         <option>select something</option>
          '".while ($dbrow = mysqli_fetch_array($result)){
              echo "<option value='".$dbrow['deptname']."'>".$dbrow['deptname']."</option>";}."'
        </select>';

    echo '<tr><td>'.$row['name'].'</td><td>'.$move.'</td></tr>';}

I am trying to display dropdown list inside the table. However whenever I apply while(...) codes, it displays an error.

shouldn't HTML + '".PHP."' + HTML be the correct way?

Upvotes: 0

Views: 49

Answers (3)

Professor Abronsius
Professor Abronsius

Reputation: 33804

Generate the select menu before entering the main loop that builds the table and then rewind the recordset so that the main loop can begin

<?php
    $html='<select name="mover">
        <option selected disabled hidden>Please select something';
        
    while( $row = mysqli_fetch_array( $result ) ){
        $html.=sprintf('<option>%s',$row['deptname'] );
    }
    
    $html.='</select>';
    $result->data_seek(0);
?>

Then build the table.

<table>
<?php
    while( $row = mysqli_fetch_array( $result ) ){
        printf('<tr><td>%1$s</td><td>%2$s</td></tr>',$row['deptname'],$html);
    }
?>
</table>

Upvotes: 1

mplungjan
mplungjan

Reputation: 177684

When you use " the php is resolved so you just need to escape the html "s

while ($row = mysqli_fetch_array($result)) { 
  echo "<tr><td>$row['name']</td><td><select name=\"mover\"><option value=\"\">select something</option>";
  while ($dbrow = mysqli_fetch_array($result))
      echo "<option value=\"$dbrow['deptname']\">$dbrow['deptname']</option>";
  echo "</select></td></tr>";
}

Upvotes: 0

user8034901
user8034901

Reputation:

Don't concatenate. End your string, start your second while loop.

while ($row = mysqli_fetch_array($result)){
  $move = '<select name="mover">
    <option>select something</option>';
    while ($dbrow = mysqli_fetch_array($result)){
      $move .= "<option value='".$dbrow['deptname']."'>".$dbrow['deptname']."</option>";
    }
    $move .= '</select>';
    echo '<tr><td>'.$row['name'].'</td><td>'.$move.'</td></tr>';
}

Removed type=text from your <select>.

Replaced your echos with $move .= ... to add to the $move variable.

Be aware that, depending on the number of items in $row this would leave your HTML with multiple <select>s with the same name.

Upvotes: 1

Related Questions