user517593
user517593

Reputation: 2883

PHP: How to run this IF statement

I ran this script, but I keep getting the "did not work" message I put in it. I know that the value in the db is correct, it must be something in my PHP...

            $getadmin = "SELECT role FROM user WHERE user_id=$uid";     
            $showadmin = @mysqli_query ($dbc, $getadmin); // Run the query.

            $admin = mysqli_fetch_assoc($showadmin);
            if($admin == 'admin'){  

            echo 'You are an admin!';

            } else {

            echo 'Did not work';

            }

Upvotes: 2

Views: 92

Answers (5)

Adam Lynch
Adam Lynch

Reputation: 3369

$getadmin = "SELECT role FROM user WHERE user_id={$uid}";   //use {} around variables for interpolation
$showadmin = @mysqli_query ($dbc, $getadmin); // Run the query.

if(!$showadmin)
{
     die('<p>ERROR: DB result is null</p>');
}

while($ROW=mysqli_fetch_assoc($showadmin))//returns $ROW associative array
{
    if($ROW['role'] == 'admin')
    {  
        echo 'You are an admin!';
    } 
    else //$ROW['role']!='admin'
    {
        echo 'Did not work because it is '.$ROW['role'];
    }
}

Upvotes: 0

BugFinder
BugFinder

Reputation: 17868

fetch_assoc returns an array, not a single string

You're needing to check $admin['role'] not $admin for the value admin.

Upvotes: 3

PeeHaa
PeeHaa

Reputation: 72682

        $getadmin = "SELECT role FROM user WHERE user_id=$uid";     
        $showadmin = @mysqli_query ($dbc, $getadmin); // Run the query.

        $admin = mysqli_fetch_assoc($showadmin);
        if($admin && $admin[0]['role'] == 'admin'){  

            echo 'You are an admin!';

        } else {

            echo 'Did not work';

        }

Upvotes: 2

Naftali
Naftali

Reputation: 146310

try this:

        $getadmin = "SELECT role FROM user WHERE user_id=$uid";     
        $showadmin = @mysqli_query ($dbc, $getadmin); // Run the query.

        $role = mysqli_fetch_assoc($showadmin);
        if($role['role'] == 'admin'){  

        echo 'You are an admin!';

        } else {

        echo 'Did not work';

        }

Upvotes: 4

Nicola Cossu
Nicola Cossu

Reputation: 56397

Not tested

$row = mysqli_fetch_row($showadmin);
if($row[0] == 'admin'){ ..  

Upvotes: 3

Related Questions