问题
If I do a select in the MySQL client, I will have output that looks like this:
mysql> select * FROM `group` LIMIT 2;
+----------+---------------------+-----------------+-------------+
| group_id | group_supergroup_id | group_deletable | group_label |
+----------+---------------------+-----------------+-------------+
| 1 | 4 | 0 | defaut |
| 8 | 1 | 1 | dbdfg |
+----------+---------------------+-----------------+-------------+
How can I convert a PDO fetch
(or fetchAll
) array in a table like that?
Here's a code usage example:
$prep = $pdo->query('SELECT * FROM `group` LIMIT 2;');
$arr = $prep->fetchAll(PDO::FETCH_ASSOC);
echo renderMySQLTable($arr);
回答1:
Something close to what mysql client outputs:
$data = array(
array(
'group_id' => '1',
'group_supergroup_id' => '4',
'group_deletable' => '0',
'group_label' => 'default',
),
array(
'group_id' => '8',
'group_supergroup_id' => '1',
'group_deletable' => '1',
'group_label' => 'dbdfg',
),
);
if ( empty($data) ) {
echo "Empty set";
} else {
// determine widths of titles
$colWidths = array();
foreach ( $data[0] as $title => $value ) {
$colWidths[$title] = strlen($title);
}
// determine widths of columns
foreach ( $data as $row ) {
foreach ( $row as $title => $value ) {
if ( is_null($value) ) {
$value = 'NULL';
}
if ( $colWidths[$title] < strlen($value) ) {
$colWidths[$title] = strlen($value);
}
}
}
// generate horizontal border
$horizontalBorder = '+';
foreach ( $colWidths as $title => $width ) {
$horizontalBorder .= str_repeat('-', $width + 2) . "+";
}
$horizontalBorder .= "\n";
// print titles
echo $horizontalBorder;
echo '|';
foreach ( $data[0] as $title => $value ) {
printf(" %-{$colWidths[$title]}s |", $title);
}
echo "\n";
echo $horizontalBorder;
// print contents
foreach ( $data as $row ) {
echo "|";
foreach ( $row as $title => $value ) {
if ( is_null($value) ) {
$value = 'NULL';
}
printf(" %-{$colWidths[$title]}s |", $value);
}
echo "\n";
}
echo $horizontalBorder;
}
回答2:
non-pdo aproach though :)
function renderMySQLTable($query) {
echo `mysql -H -e"$query"`;
}
for the array it's not that hard. a few loops and you've got you need.
start from running print_r($arr)
to see it's structure
回答3:
use Table, and give a bit of style in css.
echo "<table class='datasheet'>";
foreach($arr as $a)
{
echo "<tr>";
foreach($a as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
来源:https://stackoverflow.com/questions/5566621/in-php-how-to-display-array-contents-in-a-table