I'm trying to join two tables on their id
and then populate an empty array with key - values. table2
has an additional city_name
column which I'd like to use.
However, after joining the two tables on their id
with INNER JOIN, I cannot seem to access the city_name
value from the second table (but getting the values from the first table works fine).
Here's my code:
$city_list = array();
$i = 0;
$q = "SELECT * FROM table1 INNER JOIN table2 ON table1.id=table2.city_id";
$res = $mysql_query($q);
while($row = mysql_fetch_assoc($res) {
$city_list[$i]['id'] = $row['id']; // returns the id from table1, which is also identical to the city_id from table2
$city_list[$i]['population'] = $row['city_population']; // returns the city_population value from table1
$city_list[$i]['name'] = $row['city_name']; // returns null, even though the value exists in table2
$i++;
}
When printing the $city_list
, I get the appropriate id
and population
values, but the name
key has a value of null
, even though I have city names in table2
.
Just select the columns you really need.
SELECT table1.id, table1.city_population, table2.city_name
FROM table1
INNER JOIN table2 ON table1.id=table2.city_id
You could select the column names using an alias so that you can access both as you want. eg, change query to something like:
SELECT *, table2.user_name as table2_user_name
FROM table1
INNER JOIN table2 ON table1.id=table2.city_id
Preferably you shouldn't use *
if you don't need all the data. It tends to lead to more bugs & more difficult maintenance.
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.