0

I am trying to populate an html select dropdown with data from multiple columns in a mysql query.

When I retrieve the first column it populates the dropdown without issue. When I add the second or third columns I get issues. Originally I was getting blank fields, this was resolved by adding !empty().

However I am now getting values repeated in place of the blanks

 <?php
        $base = '';
        $base2 = '';
        $base3 = '';

 while($row = mysqli_fetch_assoc($resultpmb)) {
  $code=$row["id"];
  $name=$row["gw_name"];
  if (!empty(trim($row['vg_name']))){
  $vgname=$row["vg_name"];}
  if (!empty(trim($row['vm_name']))){
  $vmname=$row["vm_name"];}

$base .= "<option value=" .$code.">".$name."</option>";
$base2 .= "<option value=" .$code.">".$vgname."</option>";
$base3 .= "<option value=" .$code.">".$vmname."</option>";

}
?>
        <div class="form-group col-4 col-m-12">
         <div class="input-group">
            <span class="input-group-addon"><span class="glyphicon 
glyphicon-lock"></span></span>
<select name="base_colour1" class="form-control" id="base_colour1">
<option value="">Base...</option>
<?php 
echo "<option value=''>---- GW Golour ----</option></br>";
echo $base;
echo "<option value=''>---- Vallejo Game Golour ----</option>";
echo $base2; 
echo "<option value=''>---- Vallejo Model Golour ----</option>";
echo $base3;
?>
</select>
</div>
        </div>
2
  • Your value inside the loop is all the same which is $code Commented Dec 20, 2018 at 14:36
  • That's because they are the different fields in the same row. Commented Dec 21, 2018 at 9:31

1 Answer 1

3

It may be easier to add the strings within your test of !empty() otherwise it will always add values in - even when there aren't any...

while($row = mysqli_fetch_assoc($resultpmb)) {
  $code=$row["id"];
  $name=$row["gw_name"];
  if (!empty(trim($row['vg_name']))){
      $base2 .= "<option value=" .$code.">".$row["vg_name"]."</option>";
  }
  if (!empty(trim($row['vm_name']))){
      $base3 .= "<option value=" .$code.">".$row["vm_name"]."</option>";
  }

  $base .= "<option value=" .$code.">".$name."</option>";


}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.