在php生成的表单上设置默认下拉值

在php生成的表单上设置默认下拉值

问题描述:

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>

我生成了一个下拉菜单,其中包含以下代码。 如何在单击提交后将字段设置为GET变量? p>

 &lt; select&gt; 
 
&lt;?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。=“&lt; option value = \”$ id \“&gt;”。$ c;  
} 
?&gt; 
&lt; option value =''&gt; C&lt;?= $ options?&gt;  &LT; /选项&GT;  
&lt; / select&gt; 
  code>  pre> 
  div>

<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.

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.