Show results of a query to a BBDD


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";



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

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


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

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



            }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

1 answer


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%' />";


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 );

$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