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 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 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]);
Related Topics
PHP Curly Brace Syntax For Member Variable
How to List All Months Between Two Dates
Override PHP Base Dependency in Composer
PHP 5 Disable Strict Standards Error
How to Remove the Querystring and Get Only the Url
PHP Buffer Ob_Flush() Vs. Flush()
Access PHP Var from External JavaScript File
In a PHP/Apache/Linux Context, Why Exactly Is Chmod 777 Dangerous
How to Extract Text from Word File .Doc,Docx,.Xlsx,.Pptx PHP
How to PHP-Unserialize a Jquery-Serialized Form
Sending Json to PHP Using Ajax
Sqlstate[Hy000] [2002] Connection Refused Within Laravel Homestead
How to Install Curl on Windows