Display records in a select based on the id of another select

4

I have a system to sanction administrative personnel.

I recently solved the problem that changing a select called article would change the description in a textarea.

Now I have the following question:

I added to the system the possibility of showing the sections that have some articles, because it can happen that the person inflicts article 105, but the literal 2.

Then add that value to the database and another table called articles_apartados .

Up to now the system does the following:

  • Show the selection with all articles
  • Changing the select shows the description of said article in a textarea
  • Automatically in another select, the section is selected corresponding to the article
  • THE PROBLEM:

      

    in the select ALL values appear, no matter if they belong or not to the article that was selected.

    In conclusion I WANT THAT:

      

    When changing the article, continue to show its description but in the section select the literals or values contained in the section and that correspond to said article and when selected, its description appears.   Here link to explanation of the script:

    Show two data from the same table in different INPUT

    --- Here the codes --- ARTICLES table:

    id_articulo: entero primary key
    articulo: entero numero de articulo
    des_articulo: descripcion del articulo
    

    ARTICULOS_APARTADOS table:

    id_articulo_apartados: entero, primary key
    id_articulo_a: entero, este es la llave foranea del articulo
    articulo_apartado: entero, numero del literal que corresponde al articulo
    descripcion_apartado: describe el apartado
    

    Sancion.PHP

    <?php
    include "conexion.php";
    ?>
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
    <title>Listado del personal sancionado</title>
    </head>
    <body>
    <?php
    session_start();
    if(!isset($_SESSION["user_id"]) || $_SESSION["user_id"]==null){
        print "<script>alert(\"Acceso invalido!\");window.location='login.php';</script>";
    }
    ?>
    <?php include "php/navbar.php"; ?>
    <div class="container">
    <div class="row">
    <div class="col-md-6">
    </div>
    </div>
    </div>
    <h1>Generar una Sanción<br></h1>
    
    SANCION.PHP
    
        <?php
        include "conexion.php";
        global $cone;
        ?>
        <!doctype html>
        <html>
          <head>
            <meta charset="utf-8">
            <link href="styles.css" media="screen" rel="stylesheet" type="text/css" />
            <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
            <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
            <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
            <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
            <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
            <script type="text/javascript" src="jquery-1.3.2.js"></script>
    
            <title> </title>
        </head>
        <body>
        <script type="text/javascript">
        $(document).ready(function() {    
            $('#cedula1').blur(function(){
    
                $('#info1').html('<img src="loader.gif" alt="" />').fadeOut(1000);
    
                var cedula1 = $(this).val();        
                var dataString = 'cedula1='+cedula1;
    
                $.ajax({
                    type: "POST",
                    url: "comprobar_disponibilidad1.php",
                    data: dataString,
                    success: function(data) {
                        $('#info1').fadeIn(1000).html(data);
                    }
                });
            });              
        });    
        </script>
        <script type="text/javascript">
        $(document).ready(function() {    
            $('#cedula2').blur(function(){
    
                $('#info2').html('<img src="loader.gif" alt="" />').fadeOut(1000);
    
                var cedula2 = $(this).val();        
                var dataString = 'cedula2='+cedula2;
    
                $.ajax({
                    type: "POST",
                    url: "comprobar_disponibilidad2.php",
                    data: dataString,
                    success: function(data) {
                        $('#info2').fadeIn(1000).html(data);
                    }
                });
            });              
        });    
        </script>
    
    
    
    
    
          <form method="POST" name="sancion" action ="procesar4.php">
           <div>
           <label> Ingrese cedula del sancionado</label>
            <input type="text" id="cedula1" name="cedula1"><br/>
        <div id="info1"></div>
            </div>
    
    
            <div>
            <label> Ingrese cedula del sancionador</label>
            <input type="text" id="cedula2" name="cedula2"><br/>
        <div id="info2"></div>
            </div>
    
    
            <label> Ingrese tipo de sancion </label>
            <div>
              <select name="sancion">
        <?php
          $registros = mysqli_query($cone, "select * from sanciones");
          while ($reg = mysqli_fetch_array($registros)) {
              echo "<option value='$reg[id_sancion]'>" . "$reg[sancion]" . "<br/>" . "</option>";
          }
        ?>
              </select>
            </div>
            <label> Ingrese articulo inflingido </label>
            <div>
              <select name="articulo" id="articulo">
                <option value="0">Seleccione un articulo</option>
        <?php
              $registros = mysqli_query($cone, "SELECT * FROM articulos");
    
              $descripciones = '';
              while ($reg = mysqli_fetch_array($registros)) {
                  echo "<option value='$reg[id_articulo]'>" . $reg['articulo'] . "</option>";
                  $descripciones .= "<textarea id='desc".$reg['id_articulo']."' style='display: none;'>".$reg['des_articulo']."</textarea>";
              }
        ?>
              </select>
    
    
                   </select>
            </div>
            <label> Ingrese apartado </label>
            <div>
              <select name="apartado" id="apartado">
                <option value="0">Seleccione un apartado</option>
        <?php
            $id_articulo=$_REQUEST["id_articulo"];
            echo $id_articulo;
    
              $registros = mysqli_query($cone, "SELECT * FROM articulos_apartados");
               $descripciones_apartado = '';
                while ($reg = mysqli_fetch_array($registros)) {
                  echo "<option value='$reg[id_articulo_a]'>" . $reg['articulo_apartado'] . "</option>";
                  $descripciones .= "<textarea id='desc_apartado".$reg['id_articulo_a']."' style='display: none;'>".$reg['descripcion_apartado']."</textarea>";
              }
        ?>
              </select>
        <?php
              echo $descripciones;
        ?>
            </div>
            <br/>
            <textarea  id='descripcion' readonly placeholder="Seleccione un articulo" /></textarea>
            <script type="text/javascript">
            $(function() {
              // Change es un evento que se ejecuta cada vez que se cambia el valor de un elemento (input, select, etc).
              $('#articulo').change(function(e) {
                $('#descripcion').val($('#desc' + this.value).val());
              }).trigger('change');
            });
            </script>
    
            <?php
              echo $descripciones_apartado;
        ?>
            </div>
            <br/>
            <textarea  id='descripcion_apartado' readonly placeholder="Seleccione un apartado" /></textarea>
            <script type="text/javascript">
            $(function() {
              // Change es un evento que se ejecuta cada vez que se cambia el valor de un elemento (input, select, etc).
              $('#articulo').change(function(e) {
                $('#descripcion_apartado').val($('#desc_apartado' + this.value).val());
              }).trigger('change');
            });
            </script>
    
    
    
    
    
            <fieldset>
              <legend>Ingrese estado de sancion</legend>
        <?php
          $registros = mysqli_query($cone, "select * from estado_sanciones");
          while ($reg = mysqli_fetch_array($registros)) {
              echo "<label>";
              echo '<input type="radio" name="estado" value="' . $reg["estado_id"] . '">' . $reg["estado"];
              echo "</label>";
          }
        ?>
         </fieldset>
          <br/>
    
          <label> Ingrese Fecha inicial de la sancion</label>
            <div>
              <script>
              $( function() {
                $( "#fecha1" ).datepicker();
              } );
              </script>
              <input type="text" name="fecha1" id="fecha1"></p>
            </div>
            <label> Ingrese Fecha Final de la sancion</label>
            <div>
              <script>
              $( function() {
                $( "#fecha2" ).datepicker();
              } );
              </script>
              <input type="text" name="fecha2" id="fecha2"></p>
            </div>
    
    
            <label> Ingrese observacion </label><br/>
            <input type="text" id="observacion" name="observacion"><br/>
            <input type="submit" value="enviar">
          </form>
          <script src="javascript/valida_sancion.js"></script>
        </body>
        </html>
    

    Example:

    Database (Articles):

    id_articulo:1, 
    articulo: 101, 
    desc_articulo:Molestar las instalaciones,
    

    Database (Article_part)

    id_articulo_a:1 
    articulo_apartado 1: estando en horario de trabajo
    
    id_articulo_a:1 
    articulo_apartado 2: estando en horario de descanso
    
    id_articulo_a:1 
    articulo_apartado 3: estando sin trabajar.
    
    Ingrese articulo: 101(select) 1,2,3(select)
    
    MUCHAS GRACIAS
    
        
    asked by Victor Alvarado 31.01.2017 в 22:06
    source

    1 answer

    4

    I've seen some small error in your code, you have not correctly concatenated your options and some simple quotes.

    Your code:

    echo "<option value='$reg[id_articulo_a]'>" . $reg['articulo_apartado'] . "</option>";
                      ^^^^    ^^^^^^^^^^^^^^
    

    Updated:

    echo "<option value='".$reg['id_articulo_a']."'>" . $reg['articulo_apartado'] . "</option>";
    
      

    Note: check your code, there are a few wrong concatenated, I just put one as an example.

    Now let's see your question, how could we show our option according to the selected article in another select . I'm going to make a simple form, with that data, I have also modified your action , we will send it via AJAX , for this we change the send button by button and remove the attribute action and add an identifier ID to our form.

    The example could look like this:

    sancion.php

    <!DOCTYPE html>
    <html>
    <head>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><!-- libreria jQuery -->
    
      <script>    
        $(document).ready(function(){
    
          //Modificamos option de nuestro 'SELECT'
          $("#articulo").change(function(){
    
              $.ajax({
                url:"cambiar-datos-select.php",
                type: "POST",
                data:"id_select="+$("#articulo").val(),
    
                success: function(opciones){
                  $("#apartado").html(opciones);
                }
              });
          });
    
    
          //Formulario procesar4
          $(document).on('submit', '#frm-sancion', function() {
    
            //Obtenemos datos formulario
            var data = $(this).serialize();  
    
            $.ajax({            
              type : 'POST',
              url  : 'procesar4.php',
              data : data,
              success :  function(data) { 
                $(".result").html(data); 
              }
            });    
    
            return false;
    
          });
    
        }); //Fin documento
      </script>
    
    </head>
    <body>
    
    <form id="frm-sancion" method="POST" name="sancion">
      <label> Ingrese articulo inflingido </label>
      <select name="articulo" id="articulo">
          <option value="0">Seleccione un articulo</option>
          <?php
            //Conexion
            require'conexion.php';
    
            $registros = mysqli_query($cone, "SELECT * FROM articulos");
    
            $descripciones = '';
            while ($reg = mysqli_fetch_array($registros)) {
              echo "<option value=". $reg['id_articulo'].">"  . $reg['articulo'] . "</option>";          
            }
          ?>
      </select>
    
      <label>Ingrese apartado</label>
      <select id="apartado" name="apartado"> 
        <option value="0">Seleccione primero un articulo</option> 
      </select>      
    
      <button type="submit">Enviar</button>
    </form>
    
    <div class="result"><!-- Resultado AJAX procesar --></div>
    
    </body>
    </html>
    

    change-data-select.php

    <?php   
        //Si esta definida la variable Ajax y no es NULL.
        if(isset($_POST['id_select'])) { 
    
            //Conexion
            require'conexion.php';
    
            //Obtenemos el valor de la variable de Ajax (es decir, el ID).
            $id_select = mysqli_real_escape_string($cone,$_POST['id_select']);      
    
            //Sentencia -> mostramos resultao segun el 'ID' de nuestro articulo via AJAX.
            $sql = mysqli_query($cone, "SELECT * FROM articulos_apartados WHERE id_articulo_a='$id_select'");                                           
    
            echo "<option value=0>Selecciona tu apartado</option>"; //Si no quieres mostrar este mensaje, podrias quitarla.
    
            //Comprobamos existencias.
            if (mysqli_num_rows($sql) > 0) {
    
                //Salida data.                          
                while ($reg = mysqli_fetch_array($sql)) {
                    //Obtenemos datos asociados desde la Base de datos.
                    $id_bd = $reg['id_articulo_a'];
                    $artic_apartado = $reg['articulo_apartado'];
                    //Option modificado :)              
                    echo "<option value='$id_bd'>" . $artic_apartado . "</option>";                                                             
                }
            } mysqli_close($cone);  //Cerramos conexión.   
        }        
    ?>  
    

    I advise you to use prepared statements , they are very useful against SQL Injections. p>     

    answered by 04.02.2017 / 13:28
    source