How to Get Column Names from Pdo's Fetchall Result

How to get column names from PDO's fetchAll result?

There are many duplicated questions but all answers are beyond any reason, offering complicated solutions involving running extra queries etc.

While the solution is right here: when using fetchAll(), you already have all the column headers in the $result variable

$headerNames = $result ? array_keys($result[0]) : [];

now you can foreach over $coulmnNames to get the table header and the foreach over $result to display the results.

<table class='table'>
<tr>
<?php foreach($coulmnNames as $name): ?>
<th><?= $name ?></th>
<?php endforeach ?>
</tr>
<?php foreach($result as $row){ ?>
<tr class="table-row">
<?php foreach($result as $value){ ?>
<td><?= $value ?></td>
</tr>
<?php endforeach ?>
</table>

How to get column names and values from a single-row resultset with PDO?

No need to do array_search(), do like below:-

function story($id) {
global $db;
$sql = "select * from users where id = :aid limit 1";
$st = $db->prepare($sql);
$st -> execute([":aid" => $id]);
$row = $st->fetch(PDO::FETCH_ASSOC);
if(count($row)>=1){
foreach ($row as $column => $value) {
echo "<div class='title'>" . $column . "</div>\n" .
echo "<div class='story'>" . $value. "</div>\n";
}
}
}

How can I get column names from PDOStatement?

The simple answer to this is to cast the item that you pass to array_keys() to an explicit (array) - that way, arrays are unaffected but objects become the correct type:

$this->columns = empty($this->rows) ? array() : array_keys((array) $this->rows[0]);

PDO get result index by column name

There's no way to do it with any PDO flags.

Here' my suggested converting script, it's very small:

$result = [];
foreach($array as $arr) foreach($arr as $k=>$v) $result[$k][] = $v;

print_r($result);


Related Topics



Leave a reply



Submit