Aki Aki - 2 months ago 7
PHP Question

if-else statement not working correctly in while loop

I'm not sure what exactly I'm doing wrong here. I'd like to get an extra link if a user is an admin, and the link should be void if the user is a member. But I get the extra link that should be for admins only even if I'm logged in as a member. What am I doing wrong in my code?

$connect=mysqli_connect("$db_server", "$db_user", "$db_password", "$db_database");
$query="SELECT admin FROM `$table_members`";
$result=mysqli_query($connect, $query);
while ($row=mysqli_fetch_assoc($result)) {
$admin = $row['admin'];
if ($admin=="Administrator") {
echo "<a href=\"admin.php\">Admin Panel</a>";
}
else {
echo "";
}
}


Thanks for the help in advance!

Answer

I can't see any query which make the difference b/w admin and member, your code simply retrieving admin column and going through every value and printing the link whenever it matches.

Don't you think your query would be something like with a unique key plus you need to only check once instead of while loop

$query="SELECT admin FROM `$table_members` where id='uniqueid'";

or

$query="SELECT admin FROM `$table_members` where userID_email='uniqueid'";
$result=mysqli_query($connect, $query);
$row_cnt = mysqli_num_rows($result); // see if match found
if($row_cnt>0) { // if false mean unknown user
   $row=mysqli_fetch_assoc($result);
    $admin = $row['admin'];
    if ($admin=="Administrator") {
        echo "<a href=\"admin.php\">Admin Panel</a>";
    }
    else {
        echo "";
    }
}
Comments