0

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 ...
2
  • 1
    mysqli_fetch_array fetches one role Commented Jul 23, 2016 at 10:37
  • 1
    while($rol = mysqli_fetch_array($roles)) { echo $rol['nombreRol'].'<br>'; } Commented Jul 23, 2016 at 10:39

2 Answers 2

3

I think you need to fetch the results in a loop

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

if($roles){
    while( $rows=mysqli_fetch_object($roles) ){
        echo $rows->nombreRol.'<br>';
    }   
} 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.