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
PHP Remove Commas from Numeric Strings
Convert PHP Array to JSON Tree
Executing Git Commands via PHP
How to Get an Option Previously Set with Curl_Setopt()
PHP Twitter API - How to Pull in Multiple Users Tweets
Postgres Now() Timestamp Doesn't Change, When Script Works
PHP Values of One Array to Key of Another Array
Doctrine: Update Discriminator for Single_Table Inheritance
Why Doesn't Sprintf() Output Anything
What Is the ASP.NET Equivalent to PHP's Echo
Show Name Instead of Id from Different Table
What Do \R and \N Mean in PHP (And Other Languages)
How to Pass Parameters from Bash to PHP Script
Check If Variable Starts with 'Http'
Dates Not Casting After Upgrading to Laravel 7
Comparing Floats - Same Number, But Does Not Equal