chenci
chenci

Reputation: 113

PHP and mysql: how can i make selected option stay selected in s Combo after submit

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

Upvotes: 1

Views: 1038

Answers (2)

Kai Qing
Kai Qing

Reputation: 18833

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

Upvotes: 1

Petah
Petah

Reputation: 46040

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

Upvotes: 0

Related Questions