views:

96

answers:

2

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 confirmation.

+2  A: 
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 ;)

Danten
Just enable table borders, and maybe spit out a little CSS to customize the <th> headers if you want (I often use a background color on headers).
TravisO
Of course, you can strip out the HTML table elements and replace with sprintf() statements as dnagirl suggested if you really must have plain text.
Danten
If you *do* go for HTML, you need to `htmlspecialchars()` every value you put in the `<td>`​s and `<th>`​s.
bobince
+1  A: 

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.

dnagirl
Can you explain how I can get the table printed using sprintf?
Camsoft
@Camsoft, I've added a relevant example.
dnagirl
That's great. I'm having a few formatting issues but I think these can be resolved.
Camsoft