PDO deletes columns with equal names

Asked

Viewed 306 times

3

I realized that by using the PDO to execute the query below, the results are conflicting with the PhpMyadmin and the 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 table arquivo has a structure similar to this:

File table: id_file, name, number, status, id_type_file, dt_archiving, id_caching, id_user, id_numbering

The Table numeração that’s how it is:

Numbering table: id_numbering, numbering, id_filetype, status, total_documents, use

Tables have two columns in common: "status" and "id_numbering".

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

I know that the correct thing is that the columns have different names or use alias but, because there is this difference in the results of PHP and Mysql?

I’m running the query this way:

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

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

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

  • The @bfavaretto answer is correct and solves the current situation well, but the ideal in the medium term is not to use the asterisks anymore, but to name the columns individually. Consequently, you can use SELECT a.id_numeracao AS a_id_numeracao, n.id_numeracao AS n_id_numeracao etc, and the names will no longer conflict, apart from the benefit of traffic/processing only the data that will actually make use.

1 answer

4


According to this reply from the OS in English, you can instruct the PDO to include the table names in the name of each column:

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

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

$id1 = $row['arquivo.id_numeracao'];
$id2 = $row['numeracao.id_numeracao'];
  • Note: I have not yet tested this, I reply based on the answer I indicated.

  • 1

    This should be a rule for other extensions from mysql to PHP, since, so I tested the result was the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.