Home > Net >  How to loop multiple select tag and option in PHP
How to loop multiple select tag and option in PHP

Time:01-10

Multiple select tag by loop

This is what I already done, but I also want to display all value in selected in option dropdown. How do I do that?

This is the coding

$sql = $connect->prepare("SELECT * FROM mapping");

$sql->execute();
$result = $sql -> get_result();

$count = $result->num_rows;

 if($count > 0)
 {
  $namecsv = null;

    while($row = $result->fetch_assoc())
    {
           //key              //value
      $namecsv[$row['name_csv']] = $row['name_db_col'];
      
    }
    foreach($namecsv AS $name => $value)
      {
        echo "<select><option value='$value'>$name</option></select>";
      }
  }

CodePudding user response:

Move your <select> out of loop. Now you create separate <select> element for each <option>:

$sql = $connect->prepare("SELECT * FROM mapping");

$sql->execute();
$result = $sql->get_result();

$count = $result->num_rows;

 if($count > 0)
 {
    echo '<select>';

    while($row = $result->fetch_assoc())
    {
      echo "<option value='{$row['name_csv']}'>{$row['name_db_col']}</option>";
    }

    echo '</select>';
  }

CodePudding user response:

The code need to modified a bit to get the value and the list in the same drop down -

You can try this,

if($count > 0)
 {
  $namecsv = null;

    while($row = $result->fetch_assoc())
    {
           //key              //value
      $namecsv[$row['name_csv']] = $row['name_db_col'];
      
    }
    echo "<select>";
    foreach($namecsv AS $name => $value)
      {
        echo "<option value='$value'>$name</option>";
      }
    echo "</select>";
  }
  • Related