Rosamunda Rosamunda - 4 months ago 9
SQL Question

PHP: for loop showing same result twice instead of the two distinct results?

I have a SELECT query in MySQL, that I've tested in phpMyAdmin and it shows two records, where the same user (Number 1), has two roles (noAutorizado and admin):

Now, I've tried to show that in a list using a for loop, and it shows the first result twice instead the two results.
So instead of showing noAutorizado and admin, it shows noAutorizado and noAutorizado.

What's wrong with the loop?

$conectar2 = mysqli_connect(HOST, USER, PASS, DATABASE);
$buscarRoles = "SELECT userID, nombreRol
FROM rolesUsuarios
WHERE userID='$uid'
";
$roles = mysqli_query($conectar2,$buscarRoles);

if($roles){
$rol = mysqli_fetch_array($roles);
$cantRegistros = mysqli_num_rows($roles);
for ($i=0; $i < $cantRegistros; $i++) {
echo $rol['nombreRol'].'<br>';
}
} else ...

Answer

That's because the array represents a single row in the returned result set. You need to execute the mysqli_fetch_array function again to get the next record. Example:

 while($rol = mysqli_fetch_array($roles)) { echo $rol['nombreRol'].'<br>'; } 
Comments