Preserve value in a select html + php

1

I am developing a simple form with html, php and MySQL, which has validations of mandatory fields, invalid characters, etc.

html

               <?php include_once '../../includes/insert/insert_user.php'; ?>
               <h4 class="mb"><i class="fa fa-angle-right"></i> REGISTRO USUARIO</h4>

               <span class="error"><?php echo $msg; ?></span>

                <form class="form-horizontal style-form" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

                  <div class="form-group">
                    <label class="col-sm-2 col-sm-2 control-label"><b>Nombre</b></label>
                    <div class="col-sm-3">
                      <input type="text" class="form-control" minlength="3" name="name" value="<?php echo $name; ?>">
                       <span class="error">* <?php echo $nameErr; ?></span>
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="col-sm-2 col-sm-2 control-label"><b>Tipo de usuario</b></label>
                    <div class="col-sm-3">
                      <select class="form-control grey" id="tipo_usuario" name="tipo_usuario" value="<?php echo $tipo_usuario['tipo_usuario']; ?>">
                        <option value="">Seleccione</option>
                        <option value="Oficina">Oficina tecnica</option>
                        <option value="Personal">Personal</option>
                        <option value="Administrador">Administrador</option>
                      </select>
                      <span class="error">* <?php echo $tipo_usuarioErr; ?></span>
                    </div>
                  </div>

                  <div class="form-group">
                  <label class="col-sm-2 col-sm-2 control-label"></label>
                  <div class="col-sm-9">
                    <button class="btn btn-primary" name="submit" type="submit"><i class="fa fa-floppy-o"></i> GUARDAR</button>
                  </div>
                </div>
               </form>

Php and mysql (insert_user.php)

<?php

  include_once('../../includes/dbconfig.php');//mi conexion a la db
  $msg = "";

  $name $tipo_usuario = "";
  $nameErr = $tipo_usuarioErr = null;

  $valid = true;
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
     //validamos que los campos no sean vacíos y sean requeridos:
    if (empty($_POST["name"])) {
        $nameErr = "El nombre es requerido";
        $valid = false;
    } 
    else {

      $name = test_input($_POST['name']);
      // chequea que el nombre tenga letras y espacios
      if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
        $nameErr = "Solo se permiten letras y espacios, no acentos ni números";
        $valid = false;
      }
    }

    if (empty($_POST["tipo_usuario"])) {
      $tipo_usuarioErr = "El tipo de usuario es obligatorio";
      $valid = false;
    } else {
        $tipo_usuario = test_input($_POST["tipo_usuario"]);
    }

    if ($valid) {

      //Si pasa las validaciones, ejecuta el SQL
      $con->query("INSERT INTO users (name, tipo_usuario) VALUES ('$name','$tipo_usuario' )");
      echo "<script>alert('¡Usuario registrado con éxito!'); location.href='table_users.php';</script>";

    }

  }

  function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
  }

?>

Everything is fine in the insert, what happens is that when I save and leave the input name empty the selected option is lost in the "Select" and it is reset as default to the first option (Select "), instead if I do it leaving the empty select the value of the input name is not lost.

    
asked by IndiraRivas 19.10.2018 в 21:33
source

2 answers

3

Replace the section of your combo with this solution that I propose, they are a series of conditionals that will select the value chosen in said listbox.

<div class="form-group">
    <label class="col-sm-2 col-sm-2 control-label"><b>Tipo de usuario</b></label>
    <div class="col-sm-3">
        <select class="form-control grey" id="tipo_usuario" name="tipo_usuario">
            <option value="">Seleccione</option>
            <option value="Oficina" <?php if($tipo_usuario=="Oficina"){ echo "selected='selected'";}?>>Oficina tecnica</option>
            <option value="Personal" <?php if($tipo_usuario=="Personal"){ echo "selected='selected'";}?>>Personal</option>
            <option value="Administrador" <?php if($tipo_usuario=="Administrador"){ echo "selected='selected'";}?>>Administrador</option>
        </select>
        <span class="error">* <?php echo $tipo_usuarioErr; ?></span>
    </div>
</div>
  

I also make the following suggestions:

     
  • Update your connection type to Mysqli or PDO: Connect to MySQL Database

  •   
  • Use require or require_once if a script is mandatory to stop the program in case your connection or processing script is not present.

  •   
  • Verify the declaration of the variables   because they look like this: $ name $ user_type=""; and say them like this: $ name = $ user_type="";
  •   
        
    answered by 19.10.2018 / 23:53
    source
    1

    a possible solution is to use JavaScript:

    <select id="opt_ciudades">
    <option disabled>Seleccione</option>
    <option value="1">Juarez</option>
    <option value="2">Mendoza</option>
    </select>
    <script>
    document.getElementById('opt_ciudades').selectedIndex =0;
    </script>
    

    If you notice, I set the selected using the index in this case it is "0" to set the first option to be predefined.

        
    answered by 19.10.2018 в 21:58