Select option selected php mysql

0

How can I load a selected of an option through the php code? since I need to edit several data from a table, but I need to load the data of the record, but in the filters I need to appear by default the value of the result of the query, but I also appear all of the list of the combo.

I show my code.

$query2="select id_categoria, descripcion from categoria;";
                        $result2=$con->query($query2);
                        while ($reg2=$result2->fetch())
                        {
                            echo '<option value='.$reg2['id_categoria'].' selected="'.$reg['id_categoria'].'">'.$reg2['descripcion'].'</option>';
                            //echo '<option value='.$reg2['id_categoria'].' selected="'.$reg['id_categoria'].'">'.$reg2['descripcion'].'</option>';
                        }?>
    
asked by Mau España 08.05.2018 в 23:48
source

2 answers

1

If you want to fill your select option with the data of the database, it would be enough to do it this way. You do the query directly and the results load them by means of a while in option .

<?php
$query=mysqli_query($con, "select id_categoria, descripcion from categoria");
?>
<select name="categoria">
<?php 
while ($row = mysql_fetch_array($query))
{
echo "<option value='".$row['id_categoria']."'>'".$row['descripcion']."'</option>";
}
?>        
</select>
    
answered by 09.05.2018 в 00:06
0

here is some code you just have to bring two questions

1- listado de datos que van en el select  ejemplo 
tabla familia
id familia
1 papa
2 mama
3 hermano

2- selecciona el registro que vas a editar por ejemplo
tablaPersonal
id nombre idFamiliar
1  x      3

en el option es haci
<option if(in_array($familiar['id']==$personal['idFamiliar'])){echo 'selected'} value="<?php echo $familiar['id']; ?>"><?php echo $familiar['nombre'];?></option>



              <div class="form-group col-md-3">
            <label class="control-label">Conocimientos específicos</label>
            <select class="form-control input-sm selectpicker" multiple name="conocimientos[]" data-error="Es un campo obligatorio" data-live-search="true" id="conocimiento">
              <option data-hidden="true" <?php if($cadenaConocimietos[0] == '' && count($cadenaConocimietos)<=1){ echo 'selected';}?> value="NULL"></option>
              <?php foreach ($conocimientos as $conocimiento) {
              ?>
              <option <?php if(in_array($conocimiento['idConocimiento'],$cadenaConocimietos)){ echo 'selected';} ?> value="<?php echo $conocimiento['idConocimiento']; ?>"><?php echo $conocimiento['conocimiento'];?></option>
              <?php } ?>
            </select>
          </div>
    
answered by 08.05.2018 в 23:57