using Foreach to read database

Viewed 23

I'm having problems reading data from a database using foreach. I think there's something to do about it beeing an array of arrays... here's the code:

<?php
    $con = mysqli_connect('localhost', 'root', '', 'productos') or exit('No se pudo conectar con la base de datos.');

    $sql = "SELECT id, producto, marca, codigo FROM productos";

    $result = mysqli_query($con, $sql);

    if (mysqli_num_rows($result) > 0) {

      
        $productos = mysqli_fetch_assoc($result);

        foreach ($productos as $producto) {   ?>
            <div>
                <h3><?php $producto['producto'] ?></h3>
                <h4><?php $producto['marca'] ?></h4>
                <h4><?php $producto['codigo'] ?></h4>
            </div>
        <?php
        }
    } else { ?>
        <h2>No hay productos para mostrar</h2>
    <?php
    }
    ?>
3 Answers

You cannot use a foreach, as mysqli_fetch_assoc($result) only fetch the next result.
You need to process with a while($producto = mysqli_fetch_assoc($result) { ... } loop.

A) Currently, you are fetching only one row. So you can do like below:

while ($producto = mysqli_fetch_assoc($result)) {?>

B) Or You can use mysqli_fetch_all($result, MYSQLI_ASSOC); to get all data in one go.

$productos = mysqli_fetch_all($result, MYSQLI_ASSOC);

mysqli_fetch_all

mysqli_fetch_assoc

mysqli_fetch_assoc returns one row at a time, so you have to put it in a loop.

<?php
    $con = mysqli_connect('localhost', 'root', '', 'productos') or exit('No se pudo conectar con la base de datos.');

    $sql = "SELECT id, producto, marca, codigo FROM productos";

    $result = mysqli_query($con, $sql);

    if (mysqli_num_rows($result) > 0) {

      
        while ($producto = mysqli_fetch_assoc($result)) {?>
            <div>
                <h3><?php $producto['producto'] ?></h3>
                <h4><?php $producto['marca'] ?></h4>
                <h4><?php $producto['codigo'] ?></h4>
            </div>
        <?php
        }
    } else { ?>
        <h2>No hay productos para mostrar</h2>
    <?php
    }
    ?>
Related