[英]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.
我现在正在尝试使用echos对此进行测试,但仍然无法打印出任何内容。 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. $result
是mysql资源。 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; mysql_query
返回的$result
不是可以比较的字符串; it is a resource . 它是一种资源 。 You need to fetch the row from
$result
: 您需要从
$result
获取行:
$row = mysql_fetch_assoc($result)
$access = $row['access'];
if($access == 'guest') {
...
}
...
A few other issues: 其他一些问题:
mysql_real_escape_string
. mysql_real_escape_string
。 mysql
is being deprecated. mysql
。 You should try to use mysqli
(MySQL Improved) or PDO (PHP Data Objects). mysqli
(MySQL改进版)或PDO (PHP数据对象)。 I see two issues: 1. You need to use session_start(); 我看到两个问题:1.您需要使用session_start(); at the beginning.
一开始。 otherwise your if statement will not be executed.
否则,将不会执行您的if语句。 2. mysql_query($q, $con) does not return a string.
2. mysql_query($ q,$ con)不返回字符串。 it returns a record set.
它返回一个记录集。 You need to use mysql_fetch_assoc($result);
您需要使用mysql_fetch_assoc($ result); which return associative array.And from the array you retrieve your desired value by:
返回关联数组,然后通过以下方法从数组中检索所需的值:
$assoc_arr = mysql_fetch_assoc($result); $ assoc_arr = mysql_fetch_assoc($ result); $access = $assoc_arr['access'];
$ access = $ assoc_arr ['access'];
now you can compare $access. 现在您可以比较$ access。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.