Elliott
Elliott

Reputation: 3864

sql query from two tables

I have two tables (customers, admin) A user logs in by email and password, I need to check if either the email and password exists in the customer or admin table. The emails are unquie so won't have a problem there. This is for uni work, obviously I would have a better database design than this but I have to use what is given. I have this:

$email = $_POST['email']; 
$password = $_POST['password'];

$sql = "SELECT * FROM customer, admin WHERE cus_email = '$email'
 AND cus_password = '$password' OR admin_email = '$email' AND admin_password = '$password'";

Am not very good with Joins so I havent attempted one on this.

Thanks for any help :)

Upvotes: 1

Views: 183

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 755094

You really need a UNION rather than a JOIN here:

SELECT username
  FROM Customer
 WHERE cus_email = ? AND cus_password = ?
UNION
SELECT adminname AS username
  FROM admin
 WHERE admin_email = ? AND admin_password = ?

You should either use placeholders - the question marks - or protect yourself against SQL Injection attacks. There are functions to help you do that in PHP.

Upvotes: 3

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171589

SELECT cus_id as id, 'false' as IsAdmin 
FROM customer
WHERE cus_email = '$email' 
    AND cus_password = '$password' 
UNION ALL    
SELECT admin_id as id, 'true' as IsAdmin
FROM admin
WHERE admin_email = '$email' 
    AND admin_password = '$password'";

Upvotes: 2

Related Questions