如果你想在任何情况下获得任何查询的列名,那就不那么容易了。
如果返回至少一行,您可以直接从此行获取列。
但是当您想要在没有结果显示表/导出到CSV时获取列名时,您需要使用不是100%可靠的PDO函数。
// sample query - it might contain joins etc.
$query = 'select person.name, person.family, user.id from persons LEFT JOIN users ON persons.id = user.person_id';
$statement = $pdo->query($query);
$data = $statement->fetchAll(PDO::FETCH_CLASS);
if (isset($data[0])) {
// there is at least one row - we can grab columns from it
$columns = array_keys((array)$data[0]);
}
else {
// there are no results - no need to use PDO functions
$nr = $statement->columnCount();
for ($i = 0; $i < $nr; ++$i) {
$columns[] = $statement->getColumnMeta($i)['name'];
}
}