关于下拉列表单击按钮时,选择所选项目

时间:2012-06-15 05:02:57

标签: php html css database

我有一个名为reg.php的表单,其操作是reg.php,我希望在单击提交时保持选中所选的下拉值,到目前为止我所做的工作如下所示

我已检查过发布的问题,但我无法将其与我的代码相匹配

<?php
if( $_POST['registerbtn']){
$selected_value = $_POST['selectID'];
$query = mysql_query("SELECT  linecard_name FROM selection WHERE select_id = '$selected_value'");
$rows=mysql_fetch_assoc($query); 
$linecard_name= $rows['linecard_name'];
$sql = "SELECT select_id, linecard_name FROM selection " . "ORDER BY linecard_name";
$rs = mysql_query($sql);

while($rownw = mysql_fetch_array($rs)){
if(  $rownw['linecard_name'] == $linecard_name)  {
$options = "<option  selected =selected  value=".$rownw['select_id']."> " .$rownw['linecard_name']. " </option> ";
}
}
}

require("./connect.php");
$sql = "SELECT select_id, linecard_name FROM selection ". "ORDER BY linecard_name";
$rs = mysql_query($sql);
while($rownw = mysql_fetch_array($rs)){
$options .= "<option value = ".$rownw['select_id']." > ".$rownw['linecard_name']. " </option> ";
} 
mysql_close() ;

$form = "<form action='./reg.php'  method='post'> 
<table>
<tr>
<td>  </td>
<td>  <font color='red'> $errormsg </font> </td> 
</tr>

<tr>
<td> Select  Linecard </td> 
<td> <Select name='selectID' >  <option value = '0'>  Select  from here </option> $options  </select></td> 
</tr>

<tr> 
<td  > <input type='submit' name='registerbtn' value='Register' />   </td> 
</tr> 
</table> 
echo $form;

单击注册按钮之前的select语句用于填充数据库的下拉列表, 我只希望当用户完成特定选择并单击注册按钮时,所选项目仍保持选中状态, 在这种情况下,我的代码再次填充下拉列表但现在选择了用户选择的项目,但没有清除下拉列表中填写的先前项目,即在单击注册按钮之前, 请帮忙

1 个答案:

答案 0 :(得分:1)

我发现用变量做这个是最干净的,比如:

while($rownw = mysql_fetch_array($rs)){
  $selected = '';
  if ($rownw['select_id'] == $selected_value){
    $selected = 'selected="selected"';
  }
  $options .= "<option value = ".$rownw['select_id']." $selected > ".$rownw['linecard_name']. " </option> ";
}