I have three tables safe_workers, safe_companies and safe_customers
which are used to store different account types. Upon login, I need a query to lookup the LoginEmail and LoginPassword columns in all three tables and return the match based on the login form passed by the login page.
I am a beginner to MySQL and tried the following but obviously it returns an error .
select safe_companies.LoginEmail,ID
from safe_companies,safe_customers
WHERE LoginEmail='.$_POST[InEmail].' AND LoginPass= '.$_POST[InPass].'
I dont want to compare tables just want to match
If I'm understanding your question well:
What you're looking for are http://dev.mysql.com/doc/refman/5.0/en/join.html
If both tables have a colum named LoginEmail.
SELECT
sco.LoginEmail
FROM
safe_companies AS sco
INNER JOIN
safe_customers AS scu ON (sco.LoginEmail = scu.LoginEmail)
WHERE
sco.LoginEmail = '" . $_POST['InEmail'] . "' AND
scu.LoginPass = '" . $_POST['InPass'] . "'
If not, please provide more info, like table structures.
You can use the UNION
statement to accomplish that. Try this:
$dbh = new PDO('...');
$where = 'WHERE LoginEmail = :email AND LoginPass = :pass';
$query = [];
foreach (['safe_workers', 'safe_companies', 'safe_customers'] as $table) {
$query[] = "(SELECT LoginEmail, ID FROM {$table} {$where})";
}
/*
* This will become something like this:
* (SELECT LoginEmail, ID FROM safe_workers WHERE LoginEmail = :email AND LoginPass = :pass)
* UNION
* (SELECT LoginEmail, ID FROM safe_companies WHERE LoginEmail = :email AND LoginPass = :pass)
* UNION
* (SELECT LoginEmail, ID FROM safe_customers WHERE LoginEmail = :email AND LoginPass = :pass)
*/
$stmt = $dbh->prepare(implode(' UNION ', $query));
$stmt->bindParam(':email', $_POST['inEmail']);
$stmt->bindParam(':pass', $_POST['inPass']);
if ($stmt->execute()) {
var_dump($stmt->fetch(PDO::FETCH_ASSOC));
}
Note: I'm using PDO to prepare a statement and escape POST data. Take a look at its manual.
I am making an assumption based on your question details that the LoginEmail and LoginPass value for a particular user will only exist in one of the three tables. If that is the case you can use a UNION like below.
SELECT a.LoginEmail, a.ID
FROM (
SELECT LoginEmail, ID FROM safe_workers
UNION
SELECT LoginEmail, ID FROM safe_companies
UNION
SELECT LoginEmail, ID FROM safe_customers
) AS a
WHERE a.LoginEmail = 'InEmail' AND a.LoginPass= 'InPass';
However, this could cause all sorts of bad.