Michael Bourbonnais Michael Bourbonnais - 1 year ago 55
PHP Question

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

I have a form with a drop-down menu that is populated by a while statement, pulling an array from a database in mysql. I am trying to add a selected attribute for one of the options, which I have stored elsewhere on the page in the variable $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);
return $type_set;

<select name="type">
$type_set = find_all_types();
while ($type = mysqli_fetch_assoc($type_set)){
<option value= "<?php echo $type['type'] ?>"><?php echo $type['type'] ?></option>
<?php } ?>

I'm not sure if there is a better way to accomplish this, or if I can make it work using this while statement. It was pretty hard to research this, I couldn't find the same situation, most search results people were populating their drop-down menus with individually written options.

I am aware that mysql commands are deprecated, working on that.

Answer Source
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>

but it looks pretty messy - jumping in and out of php - I would stay in it:

               $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>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download