Hi,
Trying to get myself back into PHP but getting a little stuck and thinking I have been looking at this far too long to see what is probably obviously wrong!
Following a tutorial from here I created a function as part of an access page to check if the user is logged in, set an active session and what role the user has and then use it to determine whether access should be granted to a page. Everything so far is working up to determining the users role. I know it’s not working because the control element refuses to let the user see a page because their role is not ‘Administrator’.
Anyway, the function:
function userHasRole($role)
{
include '../includes/db-connect.inc.php';
try
{
$sql = "SELECT COUNT(*) FROM users
INNER JOIN userrole ON users.id = userid
INNER JOIN role ON roleid = role.id;
WHERE username = :username AND role.id = :roleId";
$s = $PDO->prepare($sql);
$s->bindValue(':username', $_SESSION['username']);
$s->bindValue(':roleId', $role);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error searching for author roles.';
echo $error;
exit();
}
$row = $s->fetch();
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
And the database table values:
mysql> select * from role;
+---------------+--------------------+
| id | description |
+---------------+--------------------+
| Administrator | Full access rights |
| Member | Limited access |
+---------------+--------------------+
2 rows in set (0.00 sec)
mysql> select * from userrole;
+--------+---------------+
| userid | roleid |
+--------+---------------+
| 1 | Administrator |
| 2 | Member |
+--------+---------------+
2 rows in set (0.00 sec)
mysql> select * from users;
+-----------+----------+-----------------------+----------+---------------------
-------------+----+
| firstname | lastname | email | username | password
| ID |
+-----------+----------+-----------------------+----------+---------------------
-------------+----+
| Test | User1 | [email]test@gmail.com[/email] | Lee7997 | bcd4c48cac866845f881
29813be42bff | 1 |
| Test | User2 | [email]test2@gmail.com[/email] | Lee1234 | 2a8b9e5416d2df83754f
500d2a72bcb4 | 2 |
+-----------+----------+-----------------------+----------+---------------------
-------------+----+
2 rows in set (0.00 sec)
In the control page I have this:
if (!userHasRole('Administrator'))
{
$error = 'User is not an admin.';
echo 'Logged in as: ' . $_SESSION['username']; /* Check if session data is available - Remember to remove this */
echo $error;
exit();
}
Every time I get the user is not an admin message. Any help appreicated