Rosamunda Rosamunda - 4 months ago 10
SQL Question

PHP: For loop that repeats the first item instead of looping through all items?

I have a MySQL query that requests a list of items.

I fetch for them and want to display every item with a for loop, but it shows me just the first item repeated, instead of every item.

Why?

<?php

$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$query = " SELECT cursoID, nombreCurso, estadoCurso
FROM cursos
WHERE estadoCurso='abierto'";
$buscarCurso = mysqli_query($conectar,$query);
$curso=mysqli_fetch_assoc($buscarCurso);
$totalRows = mysqli_num_rows($buscarCurso); //There are 3 rows of results

echo $totalRows;

for ($i=0; $i < $totalRows; $i++) {
echo '<br>';
echo $curso['nombreCurso'];
echo '<br>';
}
?>


The intended result is:

Curso 1

Curso 2

Curso 3

And instead I get

Curso 1

Curso 1

Curso 1

Answer

Your loop should be fetching from the result set on every iteration. The standard way (as in many examples given in the PHP documentation) is that you do this in the while condition:

$totalRows = mysqli_num_rows($buscarCurso); //There are 3 rows of results
echo $totalRows;
while ($curso=mysqli_fetch_assoc($buscarCurso)) {
    echo '<br>';
    echo $curso['nombreCurso'];
    echo '<br>'; 
}
Comments