PHP和mysql:如何在提交后使选定的选项在s Combo中保持选中状态

时间:2012-02-15 02:04:38

标签: php mysql combobox

我在stackoverflow中搜索,我得到的唯一东西就像this。我想用这个代码

<select class="input_select" name='nombre_compania'><?
    msqlcon_catering(); //which is the function i made that connects to the database
    $query = "SELECT * FROM compania ORDER BY id DESC";
    $result = mysql_query($query);
    while ($r = mysql_fetch_array($result))
    {
      echo "<option value=\"". $r['id'] ."\">". $r['compania_nombre'] ."</option>"; 
    }?>
</select>

当用户选择某个选项时,如果他错过了某些内容或他说错了,请在提交表单后保持选中状态。 感谢

2 个答案:

答案 0 :(得分:1)

<?php
$selected = null;
if(isset($_POST['nombre_compania']))
{
    $selected = $_POST['nombre_compania'];
}

?>

<select class="input_select" name='nombre_compania'><?
    msqlcon_catering(); //which is the function i made that connects to the database
    $query = "SELECT * FROM compania ORDER BY id DESC";
    $result = mysql_query($query);
    while ($r = mysql_fetch_array($result))
    {
      echo "<option value=\"". $r['id'] ."\" ".($selected == $r['id'] ? 'selected=\"selected\"': '').">". $r['compania_nombre'] ."</option>"; 
    }?>
</select>

答案 1 :(得分:0)

<select class="input_select" name='nombre_compania'><?
    msqlcon_catering(); //which is the function i made that connects to the database
    $query = "SELECT * FROM compania ORDER BY id DESC";
    $result = mysql_query($query);
    while ($r = mysql_fetch_array($result))
    {
      echo "<option value=\"". $r['id'] ."\"" . (isset($_REQUEST["nombre_compania"]) && $_REQUEST["nombre_compania"] == $r['id'] ? " selected='selected'" : "") . ">". $r['compania_nombre'] ."</option>"; 
    }?>
</select>