Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate column names after JOIN in MySQL with PHP

Tags:

php

mysql

Consider two tables:

t1          t2
A   B       A   C
------      -----
1   2       3   4

I run this code:

$q = mysql_query("SELECT * FROM t1 LEFT JOIN t2 ON 1=1");
print_r(mysql_fetch_all($q));

And get this result:

array(
  A => 3
  B => 2
  C => 4
)

In all the cases I tried such thing, the value from the latest joined table goes to array (index A). The question is, can I count on that?
I know about aliases, but it would be much easier for me if I could know how Mysql+php behave in such case. Thank you.

like image 240
Serge Seredenko Avatar asked Dec 07 '25 03:12

Serge Seredenko


1 Answers

Assuming that you use

mysql_fetch_assoc()

then you can count on it:

From mysql_fetch_assoc

Return Values

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 either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases.

Note

Please look at the red box. If you write new code for new projects consider moving to mysqli or PDO. And take the inpact of the deprecation of the mysql_* functions to your existing projects into account.

like image 106
VMai Avatar answered Dec 08 '25 17:12

VMai