Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch result from MySQL row with multiple same-name columns with PHP? [duplicate]

Tags:

sql

php

mysql

select * from A left join B on A.columnc=B.columnd

results returned by above SQL will include both columns of A and B.

And what if A and B have some columns with the same name?

How to retrieve the value from PHP?

like image 301
omg Avatar asked Sep 13 '09 06:09

omg


2 Answers

You probably want to be more explicit in your query. That way you can provide aliases for your columns:

SELECT
  A.foo as a_foo,
  B.foo as b_foo
FROM A
LEFT JOIN B ON A.columnc = B.columnd
like image 75
Aron Rotteveel Avatar answered Oct 21 '22 00:10

Aron Rotteveel


The answer is actualy in the PHP documentation:

"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. "

Especialy mysql_fetch_array() seems to be the best candidate when you insist on using star in the select statement:

$row = mysql_fetch_array($result, MYSQL_BOTH) 

Then you can refer to the unambigous fields by $row[name] and to the ambigous one by $row[col_number], but that limits portability of your code (maybe next version of MySQL is going to return columns in a different order?). Recommended solution is to rewrite your query and list all the required fields instead of using star and for the ambigous ones - use aliases.

like image 8
quosoo Avatar answered Oct 20 '22 23:10

quosoo