views:

19

answers:

1

Hi!

I am writing module which allows to quick add users only by providing First and Lastname (without emial address or user name). Those users are 'ghost' like, just for a temporary uses. Before adding user module needs to check if user with the same first name and last name already exists in system to avoid creating multiple ghost users with the same personal names. In other words - I need a sql query to filter users by last AND first name. As till now I was able to produce such a query:

$sql = "SELECT DISTINCT u.uid AS uid FROM users u INNER JOIN profile_values pv ON u.uid = pv.uid INNER JOIN profile_fields pf ON pv.fid = pf.fid "
                ."WHERE pf.fid = 2 AND pv.value = '%s'";
            $uid = db_fetch_object(db_query("$sql", $ln))->uid;

This query is not good enought as it finds user only by matching lastname. I am not sql expert but I have no idea how to join tables to narrow results so firstname AND lastname are matched: Something like this

WHERE pf.fid = 2 AND pv.value = 'LASTNAME' AND pf.fid = 1 AND pv.value = 'FIRSTNAME';

In my profile_fields table I have: fid = 2 -> lastname fid = 1 -> firstname

And last WHERE clause will not work. I hope those who are familiar with user - profile tables relationship in Drupal system knows what I am asking for.

+2  A: 

you need to join twice with different aliases. Something like:

$sql = "SELECT DISTINCT u.uid AS uid FROM {users} u 
INNER JOIN {profile_values} pv ON u.uid = pv.uid 
INNER JOIN {profile_fields} pf ON pv.fid = pf.fid
INNER JOIN {profile_values} pv2 ON u.uid = pv2.uid 
INNER JOIN {profile_fields} pf2 ON pv2.fid = pf2.fid
WHERE pf.fid = 2 
AND pv.value = '%s'
AND pf2.fid = 1 
AND pv2.value = '%s'";

 $uid = db_fetch_object(db_query("$sql", array($ln, $fn)))->uid;

Also with drupal you should put {} around table names.

Jeremy French
You are good. It worked like a charm and so clean query. I tried to see how Views module will construct it but it produced much dirty one ;-)
Lukasz
Yes. I knew about {}. Just pasted it from my query generator.
Lukasz