Show results of a query to a BBDD

2

Good, I have this PHP code, with a database with the table "images" and with the fields: "id", "category" and "url". When I try to select all the images in a category, it only returns the first image of that category with the following notification:

  

Notice: Undefined offset: 1 in C: \ xampp \ htdocs \ projects \ 11 \ index.php on line 31

My PHP code is as follows:

            $imagen_buscar = "Habitaciones";

            require_once("conexion-bd.php");

            try{

                $sql_buscar = $mysqli->stmt_init();
                $sql_buscar->prepare("SELECT url FROM imagenes WHERE categoria=?");
                $sql_buscar->bind_param("s", $imagen_buscar);
                $sql_buscar->execute();

                $resultado = $sql_buscar->get_result();
                //$fila = $resultado->fetch_row();
                $fila = mysqli_fetch_array($resultado);

                print_r($fila);

                for($i=0; $i<5; $i++){



                    print_r("<img src='/proyectos/11/galeria/".$fila[$i]."' alt='Imagen buscada' width='50%' />");

                }

                unset($mysqli);

            }catch (Exception $mysqli_ex3){

                die("Se produjo el siguiente error: " . "<br/>" . $mysqli_ex3->getMessage() . "<br/>" . $mysqli_ex3->getCode() .  "<br/>");
            }
    ?>
    
asked by Jopimar 16.12.2017 в 12:53
source

1 answer

2

The error comes up because you try to access in for an array per key / index, which does not exist.

Try a foreach :

foreach( $fila as $url ) {

    echo "<img src='/proyectos/11/galeria/{$url}' alt='Imagen buscada' width='50%' />";
}

Edit:

First of all we have removed the failure of Notice: Undefined offset: ... , responding now to your comment:

So that your code works in the whole, that is to say, removing some faults, eg. mix the API and get the result, it would be your code as follows:

....

$sql_buscar = $mysqli->stmt_init();
$sql_buscar->prepare( "SELECT url FROM imagenes WHERE categoria=?" );
$sql_buscar->bind_param( "s", $imagen_buscar );
$sql_buscar->execute();

$resultado = $sql_buscar->get_result();

while ( $fila = $resultado->fetch_assoc() ) {

  echo "<img src='/proyectos/11/galeria/{$fila['url']}' alt='Imagen buscada' width='50%' />";
}

...
    
answered by 16.12.2017 / 13:01
source