Query display result with while() or foreach()

Viewed 454

I was messing around with how to do queries from MySQL and show them on PHP and I stumbled upon something:

This is the table I'm doing the query to:
This is the table im doing the query to

$query = mysqli_query($conexion, "SELECT * FROM notas");

while($nota = mysqli_fetch_assoc($query)){
    var_dump($nota);
    echo $nota["Descripcion"];
}

Whenever I use a while() to display all the results of the query, it works. This table have 2 rows and both of them are showing.

Result of the var_dump($notas):
Result of the var_dump($notas)

But whenever I use a foreach(), it just returns me the last result of the query.

$query = mysqli_query($conexion, "SELECT * FROM notas");

foreach(mysqli_fetch_assoc($query) as $valor){
    var_dump($valor);
}

Result of the var_dump($valor):
Result of the var_dump($valor)

Is there any reason why? I'm doing something wrong in the foreach() loop? I really can't tell. I would just say "fudge it", accept it and only use while loops to display queries, but, you know, want to know if I was doing something wrong or not understanding something.

1 Answers

The second version is looping through the columns, not the rows. It's equivalent to:

$row = mysqli_fetch_assoc($query);
foreach ($row as $valor) {
    var_dump($valor);
}

You can see here that it's just fetching one row, which is an associative array, then looping through the elements of that array.

foreach (<expression> as <variable>) doesn't re-evaluate the expression every time through the loop. It executes it once, saves that array, then loops through the array elements.

The mysqli_result object is iterable, so you can do:

foreach($query as $valor) {
    var_dump($valor);
}

You can also call mysqli_fetch_all($query), which will return a 2-dimensional array of all the results, and then loop through that. But if the query returns many results, this will use lots of memory.

Related