Get MySQL query data to print in HTML

1

I have a HTML form where I want to show a series of data obtained from a query in MySQL using SQL.

Query:

    static public function obtenerAccesoriosPorCabana($idcabana){
        $ejecucion = self::Conexion();
        $sql = "SELECT a.idaccesorio, a.descripcion FROM accesorios AS a, cabanasaccesorios AS ca WHERE ca.idcabana=$idcabana AND ca.idaccesorio=a.idaccesorio;";
        $registro = $ejecucion->query($sql);
        //Creamos un array para almacenar los accesorios.
        $misaccesorios = array();
        //Recorremos el array y añadimos en él los accesorios mediante array_push.
        while($datos = $registro->fetch()){
            array_push($misaccesorios, $datos);
        }
        return $misaccesorios; //Devuelve un array asociativo.
    }

Test operation method getAccessoriesPorCabana ():

    $accesorios = BD::obtenerAccesoriosPorCabana(2);
    foreach ($accesorios as $a){
        echo $a["idaccesorio"]. " ".$a["descripcion"]."<br/><br/>";
    }

Everything OK.

HTML Code:

<form action="<?php echo $_SERVER['PHP_SELF'];?>" name="modificar" id="modificar" method="POST">
    <center>
        <h3><b>Accesorios:</b></h3><br/>
        <?php 
        $objeto_accesorios = BD::obtenerAccesoriosPorCabana($_GET["idcabana"]);
        $num_accesorios = BD::contarAccesorios();
        for($i=1; $i<=$num_accesorios; $i++){
            if(in_array($i, $objeto_accesorios)){
                echo "<br/><input type='checkbox' value=<?php echo $i; ?>' id=<?php $i ?>' name='accesorios' checked>";
            }else{
                echo "<br/><input type='checkbox' value=<?php echo $i; ?>' id=<?php $i ?>' name='accesorios'";
            }
        }
        ?>
        <input type="submit" value="Modificar" id="modificar" name="modificar" />
    </center>
</form>

Questions:

Why are not the accessories shown to me with their corresponding checkbox?

The names are obtained from the query: $ accessories ["description"], the names match the names of the images "images / xxxxx.png".

    
asked by omaza1990 12.12.2017 в 11:16
source

1 answer

2

Your function to obtain accessories per cabin does not return an associative array. Returns an array of arrays. If you want to return an associative array, you should do:

 $misaccesorios = [];
 while($datos = $registro->fetch()){
    $misaccesorios[$datos['idaccesorio']]=$datos['descripcion'];    
 }
 return $misaccesorios; //Esto SÍ devuelve un array asociativo.

Logic has other weak assumptions. For example, BD::contarAccesorios(); returns the total of available accessories, but does not include the case that there are non-consecutive IDs in the accessories table.

    
answered by 12.12.2017 / 13:05
source