Reputation: 935
I have made an SQL query from two tables. Everything works good but problem is that this two tables have the same field names and after I do not know how to display them correct, how to tell that $data['aaa'] is from table 1 and the same $data['aaa'] from table 2
here is my SQL query :
$query_str = "SELECT
cm.id,
cm.global_category_id,
cm.num,
cm.menu_lv,
cm.menu_ru,
cm.menu_en,
u.id,
u.menu_lv,
u.menu_ru,
u.menu_en
FROM products_category cm, products_global_category u
WHERE cm.global_category_id = u.id
";
and display data
<? foreach ($sub_category_list as $line) : ?>
<tr>
<td><?=$line['menu_lv']?></td> <---- here I want to display data from products_global_category u
<td><?=$line['sub_menu_lv']?></td> <---- products_category cm
<td><?=$line['sub_menu_ru']?></td> <---- products_category cm
<td><?=$line['sub_menu_en']?></td> <---- products_category cm
</tr>
<? endforeach; ?>
Upvotes: 3
Views: 3687
Reputation: 9281
Simply alias the records you wish to print out which conflict with one another, for example:
SELECT
table1.pid AS page_id,
table2.pid AS product_id
FROM
table1
LEFT JOIN
table2
ON
table1.id = table2.id
And then within your PHP you can echo them out as follows:
while ($row = mysql_fetch_assoc($res)) {
echo $row['page_id'];
echo $row['product_id'];
}
Hope this helps!
Upvotes: 1
Reputation: 5106
As a solution you can change your SQL query to give an alias to the fields that have the same name.
For example:
SELECT somefield AS othername FROM table.
In this case, the somefield
field will be available through the alias othername
.
In your case:
$query_str = "SELECT
cm.id AS cm_id,
cm.global_category_id,
cm.num,
cm.menu_lv AS cm_menulv,
cm.menu_ru AS cm_menuru,
cm.menu_en AS cm.menuen,
u.id as u_id,
u.menu_lv AS u_menulv,
u.menu_ru AS u_menuru,
u.menu_en AS u_menuen
FROM products_category cm, products_global_category u
WHERE cm.global_category_id = u.id
";
And then in your PHP:
$line['u_menulv'] //Access field menu_lv from products_global_category table
$line['cm_menulv'] //Access field menu_lv from products_category table
EDIT: In mysql_fetch_array
documentation page:
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name.
In other words, either create an alias like shown above or access the fields by the numeric index of the array.
Upvotes: 8