Show a default value in a listbox obtained from a MYSQL database

0

I have the following table that shows a list of data inserted in it:

Career Table:

To show them in the form I use the following function:

function bd_carrera_opciones()
{
$sql = "SELECT carr_id,carr FROM carrera ORDER BY carr ASC";
$res = sql2options( $sql );
  $zz=array();
$zz['--']='--- Seleccione la Carrera ---';
foreach($res as $id=>$valor)
{
   $zz[$id]=$valor;
}
return $zz;
}

showing up like this:

works perfectly, I use this script:

carr_id: {
            required: true,
            range: [1, 99]
        },

to prevent the chosen value from being

'--- Seleccione la Carrera ---'

THE PROBLEM:

I would like a default value to appear is to say something like this:

I do not know how to do it

Method to show the races:

<div class="form-group">
    <label for="esta_proy_id" class="control-label col-lg-2"><font size=3 color="red">*</font>Estado del Proyecto: </label>
    <div class="col-lg-5">

        <select class="form-control" name="esta_proy_id" id="esta_proy_id">
        <?php foreach($proyecto_estado as $i=>$proyecto_estado_temp):?>
            <option value="<?=$i?>"><?=$proyecto_estado_temp?></option>
        <?php endforeach; ?>
        </select>

     </div>
</div>

BY INSERTING THE FUNCTION OF EDUARDO FUENTES:

    
asked by Victor Alejandro Alvarado Vilo 01.12.2016 в 16:25
source

2 answers

1

This solution I like very much, personally, because it does not imply either javascript or css. It's pure html.

<select>
    <option value="" disabled selected>--- Seleccione la Carrera ---</option>
    <!-- Resto de opciones aquí -->
</select>

With your update, it would look something like this:

<div class="form-group">
    <label for="esta_proy_id" class="control-label col-lg-2"><font size=3 color="red">*</font>Estado del Proyecto: </label>
    <div class="col-lg-5">

        <select class="form-control" name="esta_proy_id" id="esta_proy_id">
        <?php foreach($proyecto_estado as $i=>$proyecto_estado_temp):?>
            <option value="<?=$i?>"<?= ($i == '--') ? ' disabled selected' : ''?>><?=$proyecto_estado_temp?></option>
        <?php endforeach; ?>
        </select>
    </div>
</div>
    
answered by 01.12.2016 в 16:30
1

Complementing Muriano's answer, if you are going to have a default option, which is dynamic in each case, you should at least have in each case the id of the option that will default to some variable.
If we assume that the id that goes by default comes in a variable called $ id_by_defect, the code could be like the following:

<?php foreach($proyecto_estado as $i=>$proyecto_estado_temp):?>
    <option value="<?=$i?>" 
        <?php if($i == $id_por_defecto){
            echo "SELECTED";
        }?> ><?=$proyecto_estado_temp?>
    </option>
<?php endforeach; ?>

This will leave only the option that is equal to your $ id_by_defect selected.
Greetings.

    
answered by 01.12.2016 в 19:22