1

i was searching in stackoverflow and the only thing i got is something like this. I want to do with this code

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

That when the user select a certain option, stay selected after submitting the form if he misses something or he put something wrong. Thanks

Community
  • 1
  • 1
chenci
  • 113
  • 1
  • 9

2 Answers2

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>
Kai Qing
  • 18,665
  • 5
  • 37
  • 57
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>
Petah
  • 44,167
  • 27
  • 153
  • 209