How to persist $ _SESSION value in select just as it was done for input?

3

I'm trying to get the value of select in $_SESSION to persist the search data on a system I'm doing, but I do not know how to apply this method to select . Can you help me?

I will save the variables after $_POST ...

<?php 

if($_POST) {
    $_SESSION['nome'] = $_POST['nome'];
}

?>
  

How do I save select as well as saved input ?

<?php
if(isset($_SESSION['nome'])){
    echo '<input type="text" name="nome" value="'.$_SESSION['nome'].'" class="form-control">';
} else {
    echo '<input type="text" name="nome" value="" class="form-control">';
}
?>
<select name="tipo" class="form-control" required>
    <option value="">Tipo</option>
    <option value="apartamento">Apartamento</option>
    <option value="casa">Casa</option>
    <option value="flat">Flat</option>
</select>
    
asked by anonymous 01.01.2016 / 18:20

2 answers

5

If I understood the question, it goes something like this:

<?php
   $s = ' selected="selected" ';
   $nome = isset( $_SESSION['nome'] ) ? $_SESSION['nome'] : '';
   $tipo = isset( $_SESSION['tipo'] ) ? $_SESSION['tipo'] : '';
?>
<input type="text" name="nome" value="" class="form-control">
<select name="tipo" class="form-control" required>
    <option value="">Tipo</option>
    <option <?php echo $tipo=='apartamento'?$s:''; ?>value="apartamento">Apartamento</option>
    <option <?php echo $tipo=='casa'       ?$s:''; ?>value="casa">Casa</option>
    <option <?php echo $tipo=='flat'       ?$s:''; ?>value="flat">Flat</option>
</select>

That is, only the previously selected option will receive the selected parameter.

If you need to check the post, you get the complete code:

<?php
   session_start();
   if( isset( $_POST['nome'] ) ) $_SESSION['nome'] = $_POST['nome'];
   if( isset( $_POST['tipo'] ) ) $_SESSION['tipo'] = $_POST['tipo'];

   $s = ' selected="selected" ';
   $nome = isset( $_SESSION['nome'] ) ? $_SESSION['nome'] : '';
   $tipo = isset( $_SESSION['tipo'] ) ? $_SESSION['tipo'] : '';
?>
<input type="text" name="nome" value="" class="form-control">
<select name="tipo" class="form-control" required>
    <option value="">Tipo</option>
    <option <?php echo $tipo=='apartamento'?$s:''; ?>value="apartamento">Apartamento</option>
    <option <?php echo $tipo=='casa'       ?$s:''; ?>value="casa">Casa</option>
    <option <?php echo $tipo=='flat'       ?$s:''; ?>value="flat">Flat</option>
</select>
    
01.01.2016 / 19:31
3

It is the same form as $_POST['nome'] only changing the value.

Try

<?php 

if(isset($_POST)) {
    $_SESSION['nome'] = $_POST['nome'];
    $_SESSION['tipo'] = $_POST['tipo'];
}

Do not forget to put session_start() at the beginning of the code to start the session.

To verify that there is

<?php

if(!empty($_SESSION['tipo'])){
     echo 'existe';
}else{
     echo 'não existe';
}
    
01.01.2016 / 18:23