user1039878
user1039878

Reputation: 1345

Can I search two tables for a Username?

I'm using the following query to find users in the 'Employer' table:

$username = mysql_real_escape_string($username);
$query = "SELECT password, salt
        FROM Employer
        WHERE Employer_Name = '$username';";

I have a second table called Clients (with the password & salt fields as well as a username field) , is it possible to search both tables for a single username?

(If any more information is required then let me know)

Upvotes: 0

Views: 166

Answers (5)

MeetM
MeetM

Reputation: 1430

If you want to know to which table the user being searched, belongs, you can try this:

$username = mysql_real_escape_string($username);
$query1 = "SELECT password, salt
    FROM Employer
    WHERE Employer_Name = '$username';";
$query=mysql_query($query1);
if(mysql_num_rows($query)>0)
    $from = 'Employer';
else
{
    $query2 = "SELECT password, salt
    FROM Client
    WHERE Client_Name = '$username';";
    $query=mysql_query($query2);
    if(mysql_num_rows($query)>0)
        $from = 'Client';
    else
        $from='none';
}

Upvotes: 0

Matt Moore
Matt Moore

Reputation: 581

You should use a UNION here.

SELECT password, salt FROM Employer WHERE Employer_Name = '$username';
UNION
SELECT password, salt FROM Clients WHERE Client_Name = '$username';"

This will return you one record set of all the values from both tables that match their where clause.

Upvotes: 1

ben
ben

Reputation: 1936

I think what you need here is a UNION:

SELECT password, salt, 'employer' as user_type
FROM Employer
WHERE Employer_Name = '$username'
UNION
SELECT password, salt, 'client' as user_type
FROM Clients
WHERE Clients_Name = '$username'

Upvotes: 5

Kevin Crowell
Kevin Crowell

Reputation: 10180

I believe you are asking to return a result where the username in Clients is also the employer name in Employer. If so, you can do a join like this. If you need some information from the Clients table, you can just add it to your select portion of the query.

SELECT E.password, E.salt
FROM Employer E JOIN Clients C ON (E.Employer_Name = C.Username)
WHERE E.Employer_Name = '$username';

Upvotes: 0

Ashley Banks
Ashley Banks

Reputation: 528

You certainly can, look into JOIN queries...

http://www.tizag.com/mysqlTutorial/mysqlleftjoin.php

Upvotes: 0

Related Questions