user3760455
user3760455

Reputation: 13

Select user if the user has data on another table

Good Afternoon.

I am trying to create a list of all the Users in my database that contain data in a certain table.

I have 2 tables.
USERS - Contains the name of all the users
DATA - Contains data relative to the user (IT isn't called DATA obviously).

Let's say i have 3 users:
Pedro;
Armando;
Henrique;

Pedro has data in the second table. "Armando" and "Henrique" Don't have any data in the other table.

I want to print the name of all users that contain data on the "data" table.

I tried to do this:

$query=mysql_query("select nome from users where nome <> 'admin' ORDER BY nome");
while ($whatever=mysql_fetch_array($query, MYSQL_ASSOC)){
    foreach ($whatever as $w){
    echo $w. '   '; //$w contains the name of all the users.
    $queryy = mysql_query("select id from users where nome='$w'");
    $idd = mysql_fetch_array($queryy);
    }

}
$conta=count($idd);
for ($i=0;$i<$conta;$i++){
    echo $idd[$i];
    $queryyy=mysql_query("select * from pp where id_user='$idd[$i]'");
}

On the table "pp", the field is id_user, as it is stated there, instead of "id" like on the users table.

I don't know how to proceed from here on out, since i am new to php.

Thanks

Upvotes: 1

Views: 47

Answers (1)

Jay Blanchard
Jay Blanchard

Reputation: 34416

A simple JOIN can get this for you -

SELECT USERS.name
FROM USERS
JOIN DATA
ON USERS.name = DATA.name

Upvotes: 1

Related Questions