0

I want to get the columns selected in query if no data are returned

 $sql = $this->em->getConnection()->prepare('
                SELECT
                    DATE_FORMAT(cus.period, "%Y") as ANNEE,
                    DATE_FORMAT(cus.period, "%m") as MOIS,
                    c.name AS PAYS,
                    co.id AS ORIGINE_ID,
                    co.name AS ORIGINE,
                FROM customs AS cus
                WHERE cp.product in (503)
                GROUP BY ANNEE, MOIS, PRODUCT, co.id , c.id
                ORDER BY ANNEE, MOIS, CAMPAGNE, PRODUCT, co.id, c.name;'
        );
$sql->execute();
$result = $sql->fetchAll();

I no data the result is an empty array, but I want in case that no data result should be an array like

$result = [ 'ANNEE', 'MOIS', 'PAYS', 'ORIGINE_ID', 'ORIGINE'
]

2
  • 2
    Even if data is returned, it doesn't include column names as the first row. Why do you need this? What are you trying to accomplish? You could perhaps add a static row to your array after executing the query. Or include a UNION in the query which first selects static values for the column names. But why? It seems like whatever you want to do there's likely a better way to do it.
    – David
    Commented Jan 17, 2019 at 12:00
  • @David, the idea is that I create the csv based on this query, and I have about 20 differents queries. Now if I have data I create the csv with columns on first row and values on next, but if I don't have data I need to create the csv only with one row, and this row will be all column name's. Commented Jan 17, 2019 at 12:04

1 Answer 1

1

getConnection() in Doctrine returns the PDO it wraps which means we can use getColumnMeta() to get the column names:

$stmt = $sql->execute();
$columnNames = array();

foreach(range(0, $stmt->columnCount() - 1) as $index) {
    $columnNames[] = $stmt->getColumnMeta($index)['name'];
}

$columnNames can then be added to your $result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.