尝试将Selected Attribute添加到while语句填充的下拉列表中,该语句使用mysql中的数组


Trying to add Selected Attribute to dropdown populated by while statement with array from mysql

我有一个带有下拉菜单的表单,它由while语句填充,从mysql中的数据库中提取一个数组。我正在尝试为其中一个选项添加一个选定的属性,该属性已存储在页面的其他地方的变量$inv_item["type"]中

function find_all_types() {
    global $connection;
    $query  = "SELECT type ";
    $query .= "FROM types ";
    $query .= "ORDER BY id ASC";
    $type_set = mysqli_query($connection, $query);
    confirm_query($type_set);
    return $type_set;
}
       <select name="type">
           <?php
               $type_set = find_all_types();
               while ($type = mysqli_fetch_assoc($type_set)){ 
           ?>
           <option value= "<?php echo $type['type'] ?>"><?php echo $type['type'] ?></option>
           <?php } ?>
       </select>

我不确定是否有更好的方法来实现这一点,或者我是否可以使用while语句来实现它。这很难研究,我找不到同样的情况,大多数搜索结果的人都在用单独编写的选项填充下拉菜单。

我知道mysql命令是不推荐使用的,正在处理这个问题。

you could do it as a comparison in the option:
<option value= "<?php echo $type['type'] ?>" <?php if($type['type'] == $inv_item["type"]){echo" selected";}?>><?php echo $type['type'] ?></option>

但它看起来很乱——进出php——我会留在里面:

        <?php
               $type_set = find_all_types();
               while ($type = mysqli_fetch_assoc($type_set)){ 
          $type_item = $type['type'];
          echo"<option value= '".$type_item."'";
           if($type_item == $inv_item["type"]){echo" selected";}
         echo" >".$type_item."</option>";
           } 
?>