简体   繁体   English

来自两个表的sql查询

[英]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. Joins不太好,所以我还没有尝试过。

Thanks for any help :) 谢谢你的帮助 :)

You really need a UNION rather than a JOIN here: 您确实需要一个UNION而不是JOIN:

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. 您应该使用占位符(问号)或保护自己免受SQL Injection攻击。 There are functions to help you do that in PHP. 有一些函数可以帮助您在PHP中完成此任务。

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'";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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