Gynteniuxas
Gynteniuxas

Reputation: 7093

How to get name from another table when ids match?

Well, I suck in here (although I'm trying to learn). I can't understand how to improve my code when I see when others answer similar question to my (I know it might duplicate) and at the moment I'm stuck at my last step finishing php file. I have a tables called "cities" where there are columns called "id" and "name" and another table called "locations" where there are columns "id" and "location". I also have code:

$query = "SELECT * FROM locations"; 
$res = mysql_query($query); 
while ($arr = mysql_fetch_array($res, MYSQL_ASSOC))
{
 echo '<b>'.$arr['id'].'</b><b>'.$arr['location'].'</b>';
}

While my code works and I get id of wanted ID, I need to get name of city and not id. IDs in both tables match. I cannot edit tables or columns. What should I add? Can it be solved without any left, join, in, etc. queries? I can't understand them despite how I'm trying...

Upvotes: 2

Views: 1743

Answers (1)

hex494D49
hex494D49

Reputation: 9235

Try this out

$r = mysql_query("SELECT l.id, c.name 
    FROM locations AS l
    INNER JOIN cities AS c ON c.id = l.id
");

while($l = mysql_fetch_array($r, MYSQL_ASSOC)){
    echo '<b>' . $l['id'] .'</b><b>' . $l['name'] . '</b>';
}

Upvotes: 1

Related Questions