Printing SELECT query results as preformatted text in PHP?

I am looking for a simple and quick way to print MySQL SELECT query results in PHP as pre-formatted text. I would like to be able to pass a request object to a function and get a listing of a set of records, for example, the MySQL client command line when executing 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          |
+----+-------------+

Basically for a general import script, I make a SELECT query and want to display the results for user confirmation.

+3
source share
2 answers

sprintf , -HTML.

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;

, , printf . PHP (s) printf tutorial .

+3
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);

, .

: ['field'] index;)

+2

Source: https://habr.com/ru/post/1741132/


All Articles