Nazmul
Nazmul

Reputation: 115

Storing Function value in a variable

My code generates only one result e.g "admin", then generates error. Would you please tell me how can i fix this and show all the result.

 while($row = mysqli_fetch_assoc($query)) { 
     $role  = $row['userrole'];
       Function RoleFunction($roles){
                if ($roles==1) {
                    echo " Admin";
                }
                else {
                    echo " User";
                 }                 
             }      
         $test =  RoleFunction($role); 
      echo "<tr>";          
      echo "<td>".$test."</td>";                
      echo "</tr>";
    }

Result : Admin

Fatal error: Cannot redeclare RoleFunction() (previously declared in E:\xampp\htdocs\meds\delete.php:50) in E:\xampp\htdocs\meds\delete.php on line 50

Upvotes: 0

Views: 42

Answers (3)

Punit
Punit

Reputation: 405

your function is in loop, it should be outside loop like this:

function RoleFunction($roles){
    if ($roles == 1) {
        return "Admin";
    } else {
        return "User";
    }
}
while ($row = mysqli_fetch_assoc($query)) {
    $role = $row['userrole'];
    // Print the role
    echo "<tr><td>".RoleFunction($role)."</td></tr>";
}

It will work for sure

Upvotes: 0

Saleh Ahmad Oyon
Saleh Ahmad Oyon

Reputation: 672

Keep your function RoleFunction($roles) outside of loop.

function RoleFunction($roles){
    if ($roles == 1) {
        return " Admin";
    }
    else {
        return " User";
    }                 
}      
while ($row = mysqli_fetch_assoc($query)) { 
    $role  = $row['userrole'];
    // Print the role        
    echo "<tr><td>".RoleFunction($role)."</td></tr>";                
}

Try the above code. It should be working.

Upvotes: 3

Dr M L M J
Dr M L M J

Reputation: 2397

I thin this will work...

Function RoleFunction($roles){
  while($row = mysqli_fetch_assoc($query)) { 
     $role  = $row['userrole'];

            if ($roles==1) {
                echo " Admin";
            }
            else {
                echo " User";
             }                 

     $test =  RoleFunction($role); 
    echo "<tr>";          
    echo "<td>".$test."</td>";                
    echo "</tr>";
   }
}

Upvotes: 1

Related Questions