elstiv
elstiv

Reputation: 377

HTML Option tag with selected value from PHP

Can you please help me out as to what I am doing wrong with this code:

<option value="">------------ Select ------------</option>
<?php while (($row = mysql_fetch_array($tech))) {
                            ?>
<option value= <?php echo $row['id'] ?> 
<?php echo $selectedtechname ?>
<?php echo "selected" ?>
                          >
 <?php echo $row['technician_name'] ?></option>
                    <?php } ?>

All variables are working fine since I used Var_dump and they echo correctly so no errors is SQL etc. What I need to do is pass a php statement in the option tag of HTML to simply select the value of $selectedtechname from the list. The value to post is $row['id'] but the selected value to show should be $selectedtechname

Thanks

Upvotes: 0

Views: 4125

Answers (2)

Jacob Benny John
Jacob Benny John

Reputation: 71

I see a similar post populate a select box with php mysql

while($row = mysql_fetch_assoc($result)) {
   if ($row['technician_name'] == $selectedtechname) {
       echo '<option   value=\"'.$row['id'].'" selected>'.$row['id'].'</option>';
   } else {
       echo '<option   value=\"'.$row['id'].'">'.$row['id'].'</option>';
   }
}

Upvotes: 1

Parangan
Parangan

Reputation: 148

You can try the following:

 $selected='';
    <option value="">Select a value</option>
    <?php
    while ($row = mysql_fetch_array($tech)) {
    ?>
       <?php
         if($selectedtechname == $row['selectedtechname'])
          {
             $selected='selected';
          }
          else
          {
            $selected='';
          }
        ?>
    <option value="<?php echo $row['id']?>" <?php echo $selected;?> ><?php echo $row['value_to_display'];?></option>

    <?php
    }
    ?>

Upvotes: 1

Related Questions