PHP how to leave select set

0

I have a select that takes the data from the database to do an insert:

	<div class="row">
        <div class="form-group col-md-2">
            <label for="marca">Marca</label>
            <?php 
            $link = open_database();
            $query = "SELECT marca_id, marca_nome FROM marca";
            $queryidmarca = mysqli_query($link, $query); ?>
            <select class='form-control' id='marca' name="veiculo['marca_id']">
                <option value="">-Selecione-</option>
                <?PHP while ($tipo = mysqli_fetch_array($queryidmarca)){ ?>
                <option value="<?PHP echo $tipo['marca_id'] ?>"><?PHP echo $tipo['marca_nome'] ?></option>
				<?PHP } ?>
        	</select>
        </div>
    </div>

I would like to know how to select the information that was saved in this select in another select that is in another form.

    
asked by anonymous 27.01.2018 / 13:29

2 answers

1

Let's break it down.

You will have 2 querys for this:

  • To fetch the value you've saved;

  • To generate input of type select with due option .

  • Here you search for the record that was previously saved and stored in a variable (it has to be 1 value only, so you need to have WHERE to search for the previously saved record):

    $query1 = "SELECT marca_id, marca_nome FROM marca WHERE registro = 20";
    ...(faz o fetch, etc)...
    $opcaoSalva = $array['marca_id'];
    

    With this variable $opcaoSalva you know the registry option that you are looking for correct! So now you are going to generate your input field of type select , and while generating option you will check if it is the same marca_id of your $opcaoSalva variable.

    $query2 = "SELECT marca_id, marca_nome FROM marca";
    ...
    while ($tipo = mysqli_fetch_array($queryidmarca)){ ?>
    
       <option value="<?php echo $tipo['marca_id'] ?>" <?php echo ($tipo['marca_id'] == $opcaoSalva) ? 'selected' : '' ?>><?php echo $tipo['marca_nome'] ?></option>
    

    Then in the while, you will generate all options, but as long as you generate, you will check that $tipo['marca_id'] is the same as $opcaoSalva , and if so, it prints selected inside the <option> tag. default of html that).

    <?php echo ($tipo['marca_id'] == $opcaoSalva) ? 'selected' : '' ?>
    
        
    28.01.2018 / 23:49
    1

    You can use the selected attribute, and make a ternary condition to print selected .

    For example:

    <select name="veiculo">
      <option <?php echo ($condicao === true) ? 'selected' : ''; ?>>Opção</option>
    </select>
    
        
    27.01.2018 / 13:34