Print results of a SELECT query as preformatted text in PHP?
I'm looking for an easy and quick way to print out the results of a MySQL SELECT query in PHP as preformatted text. What I would like is to be able to pass a query object to a function and get a printout of the recordset like the command line MySQL client does when running SELECT statements.
Here is an example of how I want it to look (i.e. ASCII):
+----+-------------+
| id | countryCode |
+----+-------------+
| 1 | ES |
| 2 | AN |
| 3 | AF |
| 4 | AX |
| 5 | AL |
| 6 | DZ |
| 7 | AS |
| 8 | AD |
| 9 | AO |
| 10 | AI |
+----+-------------+
It's basically for a generic import script, I am doing a SELECT query and want to display the results to the user for confirmatio开发者_开发知识库n.
sprintf is your friend, if you must have a non-HTML fixed width output.
ETA:
//id: integer, max width 10
//code: string max width 2
$divider=sprintf("+%-10s+%-13s+",'-','-');
$lines[]=$divider;
$lines[]=sprintf("|%10s|%13s|",'id','countryCode'); //header
$lines[]=$divider;
while($line=$records->fetch_assoc()) {
//store the formatted output
$lines[]=sprintf("| %10u | %2.2s |", $line['id'],$line['code']);
}
$table=implode("\n",$lines);
echo $table;
If you want to print out immediately instead of storing the results, use printf
instead- same syntax. There is a reasonable PHP (s)printf tutorial here.
function formatResults($cols, $rows) {
echo'<table>';
echo '<tr>';
foreach ($cols as $v) {
echo '<th>' . $v['field'] . '</th>';
}
echo '</tr>';
foreach ($rows as $sRow) {
echo '<tr>';
foreach ($sRow as $v) {
echo "<td>$v</td>";
}
echo '</tr>';
}
echo '</table>';
}
$qry = $pdo->query('DESCRIBE table');
$cols = $qry->fetchAll(PDO::FETCH_ASSOC);
$pdo->query('SELECT * FROM table');
$rows = $qry->fetchAll(PDO::FETCH_ASSOC);
formatResults($cols, $rows);
Untested but should work.
Edit: Missed ['field'] index ;)
精彩评论