简体   繁体   中英

This if statement isn't working - what am I doing wrong?

I'm trying to retrieve the access level (admin/member/guest) for the currently logged in user and depending on this, show them specific content on my page. I'm trying to test this with echos right now but still cannot get anything to print out. Could anyone give any advice?

if(isset($_SESSION['username'])){

    global $con;
    $q = "SELECT access FROM users WHERE username = '$username' ";
    $result = mysql_query($q, $con);

    if($result == 'guest')
    {
        echo "You are a guest";// SHOW GUEST CONTENT
    }
    elseif($result == 'member')
    {
       echo "You are a member"; // SHOW OTHER CONTENT
    }
    elseif($result == 'admin')
    {
        echo "You are an admin";// SHOW ADMIN CONTENT
    }

}

$result is a mysql resource. you need

if(isset($_SESSION['username'])){

    global $con;
    $q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
    $result = mysql_query($q, $con);
    $row = mysql_fetch_assoc($result);

    $access = $row['access'];

    if($access == 'guest')
    {
        echo "You are a guest";// SHOW GUEST CONTENT
    }
    elseif($access == 'member')
    {
       echo "You are a member"; // SHOW OTHER CONTENT
    }
    elseif($access == 'admin')
    {
        echo "You are an admin";// SHOW ADMIN CONTENT
    }

}

$result as returned by mysql_query is not a string that you can compare against; it is a resource . You need to fetch the row from $result :

$row = mysql_fetch_assoc($result)
$access = $row['access'];

if($access == 'guest') {
   ...
}

...

A few other issues:

  • You have a possible SQL-injection issue in your query. You should never directly insert the values of variables into your SQL queries without properly escaping them first. You might want to use mysql_real_escape_string .
  • The mysql is being deprecated. You should try to use mysqli (MySQL Improved) or PDO (PHP Data Objects).

I see two issues: 1. You need to use session_start(); at the beginning. otherwise your if statement will not be executed. 2. mysql_query($q, $con) does not return a string. it returns a record set. You need to use mysql_fetch_assoc($result); which return associative array.And from the array you retrieve your desired value by:
$assoc_arr = mysql_fetch_assoc($result); $access = $assoc_arr['access'];

now you can compare $access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM