Combobox already selected with database value

Asked

Viewed 34 times

-1

I have some combobox in the area of editing user information and I need to pull the data already selected previously by the user at registration time. I tried to do with the foreach but it didn’t work.

 <div class="form-group col-md-5" >
      <label for="inputSexo">Sexo</label>
      <select name="sexo_cliente" id="sexo_cliente" class="form-control" disabled>
         <option selected disabled="">Sexo</option>
         <?php 
            require_once "api/conexao.php";

            try {
                $prepared3 = $conexao_pdo->prepare("select * from sexo");
                $prepared3->execute();
                $result3 = $prepared3->fetchAll();

                    foreach($result3 as $resultado3) { 
                        echo "<option value='". $resultado3["cod"] ."'>". $resultado3["sexo"] ."</option>";
                    }

            } catch (PDOException $e) {
                echo "<option></option>";
            }   

            ?>
      </select>
   </div>

1 answer

0


You can solve this by checking the value registered by the user and comparing it with the values that will be placed in the options, setting as Selected (option marked by default) the sex of the user to be edited.

<div class="form-group col-md-5" >
    <label for="inputSexo">Sexo</label>
    <select name="sexo_cliente" id="sexo_cliente" class="form-control" disabled>
        <option selected disabled="">Sexo</option>
            <?php 
                require_once "api/conexao.php";

                try {
                    $prepared3 = $conexao_pdo->prepare("select * from sexo");
                    $prepared3->execute();
                    $result3 = $prepared3->fetchAll();

                        foreach($result3 as $resultado3) { 
                            // $varSexoUsuario é a variavel com valor do sexo do usuario
                            $selected = ($resultado3["cod"] == $varSexoUsuario) ? 'selected' : '';
                            echo "<option value='". $resultado3["cod"] ."' ".$selected.">". $resultado3["sexo"] ."</option>";
                        }

                } catch (PDOException $e) {
                    echo "<option></option>";
                }   
        ?>
  </select>
</div>
  • I imagine that this variable is filled with the attribute of the user who is trying to edit...

  • I got it, thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.