user780483
user780483

Reputation: 3063

set default drop down value on php generated form

I generated a drop down menu with the code below. How can I set the field to the GET variable after submit is clicked?

<select>

<?php
    $sql="SELECT c FROM problems WHERE b='$id'"; 
    $result=mysql_query($sql); 

    $options=""; 

    while ($row=mysql_fetch_array($result)) { 

    $id=$row["c"]; 
    $c=$row["c"]; 
    $options.="<option value=\"$id\">".$c; 
    } 
?>
        <option value=''>C <?=$options?>  </option>     
</select>

Upvotes: 1

Views: 3188

Answers (2)

Pradeep
Pradeep

Reputation: 1264

<select>

<?php
    $sql="SELECT c FROM problems WHERE b='$id'"; 
    $result=mysql_query($sql); 

    $options=""; 

    while ($row=mysql_fetch_array($result)) { 

    $id=$row["c"]; 
    $c=$row["c"]; 
    if($_GET['var'] == $id)
      echo '<option selected="selected" value=\"$id\">' . $c . '</option>';
    else
       echo '<option value=\"$id\">' . $c . '</option>'; 
    } 
?>

</select>

Basic idea is compare value GET data with database data and using if else condition add selected="selected" if condition matched. I am directly printing string as they will not be getting use later on.

Upvotes: 1

Thomas Minor
Thomas Minor

Reputation: 657

I'm a bit confused about what you want to know. To have an option selected by default, use the selected="selected" attribute on that option.

If you want to know how to get the submitted value in PHP, you need to assign the name attribute to the <select> tag. In general, however, you've got the idea right.

Upvotes: 0

Related Questions