Display data from B.D. in an HTML select

1

Good people, well here's my problem, I have a page in php with the html view, we go a page of all life, which is accessed after a login, I've verified that after login the important data , that is, the ID and the User's Name are passed correctly. Now, within my page I have a select from which I want to "fill" your options with information from a table in my database, that is, depending on the user's Id, different options will be shown. The user enters as a collector and must have a selection of the producers that correspond only to him. Now the problem is that I have made different attempts in different ways but I can not get the information displayed.

This is the page in question: Your code is this:

 <?php
    session_start();
    error_reporting(E_ALL ^ E_NOTICE);
   if(!isset($_SESSION['usuario']) and $_SESSION['estado'] != 'Autenticado') {
    header('Location: logeo.php');
    } else {
    $nombre = $_SESSION['usuario'];
    $id = $_SESSION['id'];
    $salir = '<a href="salir.php" target="_self">Cerrar sesión</a>';
    require('sesiones.php');
    };
    include('conexion.php');
?>

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <link rel="shortcut icon" href="img/Merico.png"/>
  <title>Grupo Merino Registro</title>
  <!-- CSS  -->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/footer.css" type="text/css" rel="stylesheet"/>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-102894505-1', 'auto');
  ga('send', 'pageview');
</script>
</head>
<body>
  <div class="navbar-fixed">
  <nav class="white" role="navigation" id="merhead">
    <div class="nav-wrapper container navbar-fixed-top">
      <a id="logo-container" href="index.html"> <class="brand-logo"><img src="img/Logino.png" style="width:15%" alt="Image"></a>
      <ul class="right hide-on-med-and-down">
        <li><h4 class="header center brown-text text-darken-2">Registro de producto para Acopiadores</h4></li>
        <li><?php echo $salir; ?></p></li>
      </ul> 
      <ul id="nav-mobile" class="side-nav">
        <li><h4 class="header center brown-text text-darken-2">Registro de produto para Acopiadores</h4></li>
        <li><p><?php echo $salir; ?></p></li>
      </ul>
      <a href="#" data-activates="nav-mobile" class="button-collapse brown-text text-darken-2">Menú</a>
    </div>
  </nav>
</div>

<div class="card-panel #009688 teal">
<center><h4>Registro del acopiador:  <?php echo $nombre; ?></h4></center>

   <div class="card-panel #80deea cyan lighten-3">    
      <div class="row">
        <div class="input-field col s4">
          <div class="selector-productor">
            <select id="productor" name="px">
              <option value="0" disabled selected>Seleccione un Productor</option>

            </select>
            <label for="nombre">Nombre de productor: </label>
          </div>
        </div>
        <div class="input-field col s4">
          <input name="kilos" type="number" class="validate" required autofocus min="1">
          <label for="kilos">Kilos: </label> 
        </div>
        <div class="input-field col s4">
          <input name="precio" type="number" class="validate" required autofocus min="1">
          <label for="precio">Precio: </label>
        </div>
      </div>
      <center><button class="btn waves-effect waves-light cyan darken-3" type="submit" value="submit"  name="registrar">Registrar<i class="material-icons right">send</i></button></center>
      </div> 
</div>

</body>

<footer class="footer.css">
  <div class="footer-copyright">
    <div class="container">
      <center><a class="brown-text text-lighten-3" href="http://www.grupomerino.com.mx/">Copyright © 2014 Grupo Merino</a></center>
    </div>
  </div>
</footer>
   <!--  Scripts-->
  <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="js/materialize.js"></script>
  <script src="js/init.js"></script>

  <script>
    $(document).ready(function() {
      $('select').material_select();
    });
  </script>
</html>

And yes, I have a separate file that handles the database connection:

    <?php
    // Parametros a configurar para la conexion de la base de datos 
    $host = "localhost";    
    $basededatos = "merino_sis";     
    $usuariodb = "root"; 
    $clavedb = "";    

    //Lista de Tablas
    $tabla_db1 = "acopiadores";         // tabla de los acopiadores.
    $tabla_db2 = "productores";         // tabla de los productores.
    $tabla_db3 = "registros_a";         // tabla de los registros de los acopiadores.
    $tabla_db4 = "registros_p";         // tabal de los registros de los productores.

    $conexion = mysqli_connect($host,$usuariodb,$clavedb,$basededatos);

    if ($conexion->connect_errno) {
        echo "La conexión a la Base de Datos ha resultado en un fallo";
        exit();
    }
?>

I do not really know what to do, I have been given the option to enter the following code inside the "SELECT" tag but all it does is that on my page there is no field for the data, nor the button or even the footer:

 <?php
            $query="SELECT id,nombre_p FROM 'productores' WHERE id_ac='".$id."'";
              $result = mysqli_query($query)
              or die("Ocurrio un error en la consulta SQL");
                mysqli_close();
              while (($fila = mysqli_fetch_array($result)) != NULL) {
                echo '<option value="'.$fila["id"].'">'.$fila["nombre_p"].'</option>';}
          ?>

Thanks in advance.

    
asked by Soul Aside 22.01.2018 в 17:18
source

1 answer

1

Well, I can think of a couple of things that are happening so at the beginning I recommend confirming the level of error that PHP will report with the following:

ini_set('display_errors', true);
error_reporting(E_ALL);

Then, you are using the functions mysqli to connect but mysql (obsolete) for the query below, this does not send any errors currently but should do so when confirming the error level.

Finally, it is not necessary to close the database since the next execution of this or other scripts could use this same connection eliminating the overhead of creating a new one in each call.

We also added a last option created by PHP outside the loop to know that our script runs completely.

In the end, thinking that you want the options to be filled in SELECT productor and that the query to your database is correct, the code would look something like this:

        <select id="productor" name="px">
          <option value="0" disabled selected>Seleccione un Productor</option>
<?php

ini_set('display_errors', true);
error_reporting(E_ALL);

  $query="SELECT id,nombre_p FROM 'productores' WHERE id_ac='".$id."'";
  $result = mysqli_query($conexion, $query) or die("Ocurrio un error en la consulta SQL");
  while (($fila = mysqli_fetch_array($result)) != NULL) {
     echo '<option value="'.$fila["id"].'">'.$fila["nombre_p"].'</option>';
  }
echo '<option>Esta es la última opción y solo es para verificar que sirve el código PHP.</option>'
?>

        </select>
    
answered by 22.01.2018 / 20:01
source