Is it possible to return the headers of a PDO query if there are no results as an array in PHP. For example:
SELECT fruit.`type` AS 'Type', fruit.`shape` AS 'Shape', fruit.`age` AS 'Age', fruit.`name` AS 'Name' FROM fruit WHERE name = :name;
$stmt = $this->db->prepare($sql); $stmt->execute([ 'name' => 'chicken' ]); return $stmt->fetchAll(PDO::FETCH_ASSOC);
Since the above will return no rows is it possible to instead return the SELECT AS so it will return:
['Type', 'Shape', 'Age', 'Name']
Advertisement
Answer
I’ve found a solution to this:
if ($stmt->rowCount() < 1) { $headers = []; foreach(range(0, $stmt->columnCount() - 1) as $index => $column_index) { $meta[] = $stmt->getColumnMeta($column_index); array_push($headers,$meta[$index]['name']); } return array_values($headers); }