Caro_deb
Caro_deb

Reputation: 279

How to echo value from a different table?

Here's a very simplified example of what I am trying to achieve :

USERS
 id      |    name          
 12      |    Phil      

ACTIONS
 sender  |  recipient
 12      |  Alice

$table = query("SELECT id, sender FROM users WHERE recipient = Alice");
foreach ($table as $row) {
$sender = $row['sender'];

echo '$sender has sent a gift to Alice';
}

This will output :

12 sent a gift to Alice

How can I get the below output instead ?

**Phil** sent a gift to Alice

Should I join the two tables ?

Upvotes: 0

Views: 63

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270301

You need a join:

SELECT u.name, sender
FROM actions a join
     users u
     on a.sender = u.id
WHERE recipient = 'Alice';

Upvotes: 1

Related Questions