PDO suppresses columns with equal names

Posted on

Question :

I noticed that using PDO to execute the query below, the results are conflicting with PhpMyadmin and Console do Mysql :

SELECT a.*, n.* FROM arquivo AS a INNER JOIN numeracao AS n ON 
                    (a.id_numeracao  =  n.id_numeracao) WHERE total_documentos=-1

The arquivo table has a structure similar to this:


File table: file_id, name, number, status , file_id,
  dt_archiving, id_debug, id_user, enumeration id

Table numeração looks like this:


Numbering table: number_name , numbering, file_type id, status ,
  total_documents, usage

Tables have two columns in common: “status” and “number_id”.

If I execute the query by PhpMyadmin or Console do Mysql the result distinguishes the columns of each table. however running with the PDO the columns in common are suppressed, and only one is displayed.

I know the correct is the columns have different names or use aliases, but why does this difference occur in PHP and Mysql results?

I’m running the query this way:

$q = $conn->prepare($select);

   $data = array();
   while ($row = $q->fetch($pdo_fetch)) {  
      $data[] = $row;   

Note: I tested the extensions mysql and mysqli and the result is the same.


Answer :

According to this SO response in English , you can instruct the PDO to include the names of the table in the name of each column:

$conn->setAttribute(PDO::ATTR_FETCH_TABLE_NAMES, true);

With this, the values of your example would be retrieved like this:

$id1 = $row['arquivo.id_numeracao'];
$id2 = $row['numeracao.id_numeracao'];


Leave a Reply

Your email address will not be published. Required fields are marked *