0

I want to select data from my database. I don't want to manually put the data how can I populate it from my database?

 <?php
              $q1 = "select * from bloodbank_facility";
            $option="";
            $q = $conn->query($q1);
            while($row1 = $q->fetch_array($q1)){
              $option = $option."<option>$row1[1]</option>";
            }
            ?>

<select name="facility_name" required>
          <?php while($row1 = mysqli_fetch_array($q1)):;?>

<option value="<?php echo $row1[0];?>"><?php echo $row1[1];?></option>

<?php endwhile;?>
          </select>

Notice: I already fixed it and thank you for your help. This is the solution that I came up with.

<select name="facility_name" required style="width:260px;">
          <?php
              $q1 = $conn->query("SELECT bloodbank_name FROM bloodbank_facility");
            
          ?>
          <?php
            while($rows = $q1->fetch_assoc()){
              $facility_name= $rows['bloodbank_name'];
              echo "<option value='$facility_name'>$facility_name</option>";
            }
          ?>
          </select>

2 Answers2

2
<?php
    $q1 = "select * from bloodbank_facility";
    $q = $conn->query($q1);
    $myselect='<select name="facility_name" required>';
    while($row1 = $q->fetch_array($q1)){
    $myselect .= '<option>'.$row1[1].'</option>';
    }
    $myselect.='</select>';
?>

<?php echo $myselect; ?>
1

This should do the trick:

<?php
    $q1 = "select * from bloodbank_facility";
    $options=[];
    $q = $conn->query($q1);
    while($row1 = $q->fetch_array($q1)){
        $options[] = "<option>{$row1[1]}</option>";
    }
?>
<select name="facility_name" required>
  <?php echo implode($options) ?>
</select>

The main thing you didn't do was have the curly braces around $row1[1] which meant PHP thought you just wanted $row1 rather than the array value.

Notice: I already fixed it and thank you for your help. This is the solution that I came up with.

<select name="facility_name" required style="width:260px;">
          <?php
              $q1 = $conn->query("SELECT bloodbank_name FROM bloodbank_facility");
            
          ?>
          <?php
            while($rows = $q1->fetch_assoc()){
              $facility_name= $rows['bloodbank_name'];
              echo "<option value='$facility_name'>$facility_name</option>";
            }
          ?>
          </select>
Sarah K
  • 363
  • 2
  • 15
  • 1
    There is never any benefit to declaring an option's `value` attribute if the value is identical to the text. It is basically unnecessary markup bloat. It is generally a good idea to html-encode values that you are injecting into an HTML document. Also, the result set object from a mysqli query can be traversed by a `foreach()` and each row treated as an associative array -- this avoids the need to make iterated calls of `fetch_...()`. See here: https://stackoverflow.com/a/66775416/2943403 – mickmackusa Sep 13 '21 at 05:39