简体   繁体   中英

MySQL Inner join output to html table in php

I have a table that is being displayed in a form, which looks like this: http://puu.sh/5VBBv.png

在此处输入图片说明

The end of the table, City, is displaying an ID of a city, which is supposed to be linked to another table ( http://puu.sh/5VBIG.png ).

在此处输入图片说明

What I've done for my INNER JOIN query is:

mysql_query("SELECT * FROM cities INNER JOIN people ON people.cityid = cities.id") or die(mysql_error());` 

and I'm trying to output it into a table:

echo "<td>" . $row['cityid'] . "</td>";

My issue is that I'm not quite sure how to actually display the cityid that corresponds to the city name. I've tried using ['name'] and other values as the value to output in the table, and I can't find any solution for this anywhere so far. I'm just learning joins, so I don't exactly have any knowledge on what I could be doing wrong. Is there anything immensely obvious?

First your use of * in the join query could be ambiguous. If cities had a name column and people had a name column, you won't know which one you're getting. Second you can do this a couple ways. I think you're trying to get a city id from a city name. If that's correct you can either make and ajax call and query it directly or define an array as follow:

$res = mysql_query("...");    
$city_ids = Array();

while ($ary = mysql_fetch_assoc($res)) {
        city_ids[$ary['name']] = Ary['id']; 
}

Then when you get the name, you just loop up $ary['name'] .

Selecting from people and joining cities makes more sense. Then select the fields you need.

SELECT people.*, cities.name as city_name FROM people JOIN cities ON people.cityid = cities.id

Then, echo $row['city_name']

 Select ID from cities city, people person where person.ID = city.ID

您正在从“城市”和“人”中选择ID,然后加入ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM