1

I have several table with similar column name in my database.

Let say TABLE 1, TABLE 2, TABLE 3 have a column named : "name". Those are not indexed columns. They contain different and independant data.

If I run a query joining these 3 tables and fetchAll() the results, there will be only one "name" entry in the resulting array since fetchAll() overwrite the column with the same name.

The regular MySQL Library let you access such results doing:

mysql_result($result,0,'TABLE1.name');

How can I let PDO append the table name before the column name like : TABLE1.name, TABLE2.name, etc.

I want to AVOID using alias in my SQL query since I have tons of tables. The only answers I found online uses alias. Is there any parameters we can feed to PDO to do what I am looking for?

Peter Lur
  • 728
  • 2
  • 12
  • 26
  • Afaik, you'll have to use `PDO::FETCH_NUM` & use the number of the column, or `FETCH_BOUND` with `->bindColumn()`, again with the number based index. – Wrikken May 07 '13 at 19:29
  • Wrikken: Any more details on how I could do this? – Peter Lur May 07 '13 at 19:35
  • It's in PHP's docs, although `var_dump()`-ing the results of `->fetchAll(PDO::FETCH_NUM)` & examining it's output will probably tell you enough to work with it. – Wrikken May 07 '13 at 20:54
  • You could also use `PDO::FETCH_NAMED`. – marver Aug 07 '18 at 06:22

1 Answers1

3

You can use aliases instead of direct column names in your SELECT statement. Something like this:

SELECT
  table1.name AS t1_name,
  table2.name AS t2_name,
  table3.name AS t3_name
-- rest of your query
vcampitelli
  • 3,168
  • 1
  • 12
  • 13
  • Please see my question above: "I want to AVOID using alias in my SQL query since I have tons of tables" -.- – Peter Lur May 07 '13 at 19:35
  • Sorry, didn't see that :P You can use `PDO::FETCH_NUM`, which _returns an array indexed by column number as returned in your result set, starting at column 0_, according to the [manual](http://php.net/manual/pt_BR/pdostatement.fetch.php). – vcampitelli May 07 '13 at 19:40