views:

31

answers:

2

Hi, thanks for viewing this. I have a db that has users, roles & user_roles. What I am trying to achieve is a login that will select users who have Admin or Associate permissions. The login then uses name and password to permit access.

My SQL syntax thus far is -

SELECT * FROM users 
LEFT JOIN ON user_roles 
ON user.id=user_roles.userid AND roleid IN (Administrator, Associate) 
WHERE username = '$username' AND password = '$password'";

I am not sure where I am going wrong.

Thanks in advance for your help.

+1  A: 

Try replacing "LEFT JOIN" by "INNER JOIN"

Sergio
Hi Sergio - I had also had a similar thought and had tried this before posting but it didn't work for me. Thank you for your input, it is really appreciated.
Ddywalgi
A: 

Here's how I'd write the query:

$stmt = $pdo->prepare("
SELECT (u.password = :password) AS password_is_correct,
  (r.roleid IS NOT NULL) AS role_is_authorized
FROM users u
LEFT JOIN ON user_roles r
  ON u.id=r.userid AND r.roleid IN (Administrator, Associate) 
WHERE u.username = :username");

$stmt->execute(array(":password"=>$password, ":username"=>$username));

This allows you to distinguish between the three conditions: (1) username does not exist, (2) password is wrong, or (3) role is not authorized.

PS: Should "Administrator" and "Associate" be quoted or something? The way you're using them, they look like identifiers rather than values.

Bill Karwin
Hi Bill - thankyou for this, Administrator and Associate are the id in user_roles and therefore identifiers, however SQL does prefer them to be in '' quotes as they are varchar not int as adding (Administrator)as an id was rejected by MySql until it was communicated as ('Administrator').An eloquent solution Bill Thankyou. I am now eager to try this.
Ddywalgi
Note that the usage of a boolean predicate in the select-list is permitted by MySQL, but in more strictly SQL-compliant databases this is not allowed. To write more portable SQL, do something like: `CASE WHEN (u.password=:password) THEN 1 ELSE 0 END CASE AS password_is_correct`
Bill Karwin
Hi Bill I am getting the following error. Undefined variable: pdo in... and also Fatal error: Call to a member function prepare() on a non-object in I will try and sort this and get back if I find an answer.
Ddywalgi
The `$pdo` variable represents a PDO object, connected to a database. See http://php.net/manual/en/pdo.construct.php
Bill Karwin
Thank you Bill. I wasn't aware of this method. Thanks very much.
Ddywalgi