开发者

Print results in MySQL format with PHP

开发者 https://www.devze.com 2023-03-08 08:47 出处:网络
Is there a way to print the results of a MySQL query in the开发者_StackOverflow中文版 same format as the terminal?

Is there a way to print the results of a MySQL query in the开发者_StackOverflow中文版 same format as the terminal?

Something like:

+--------+------------------------------+------+------+
| id     | name                         | year | rank |
+--------+------------------------------+------+------+
|  10920 | Aliens                       | 1986 |  8.2 |
|  17173 | Animal House                 | 1978 |  7.5 |
|  18979 | Apollo 13                    | 1995 |  7.5 |
|  30959 | Batman Begins                | 2005 | NULL |
|  46169 | Braveheart                   | 1995 |  8.3 |
| 109093 | Fargo                        | 1996 |  8.2 |

I am querying the database from php.

Any help would be appreciated. Thanks!


Look into sprintf/printf:

echo '+--------+------------------------------+------+------+';
echo '| id     | name                         | year | rank |';
echo '+--------+------------------------------+------+------+';

foreach (...) {
    printf('| %6s | %-28s | %4s | %4s |', $row['id'], $row['name'], $row['year'], $row['rank']);
}

You'll run into problems for anything that's longer than the predefined column size though. You can make dynamic column widths that scale to the right size by first going through your values and figuring out what the longest value is. In that case, for the horizontal lines, use str_repeat. I'll leave that as exercise for you.


Why not print using HTML? That'd be easier than ASCII


Technically...

$sql = "SELECT id, name, year, rank FROM Table"
echo '<pre>';
system("mysql mysql --user=$user_name --password=$your_password $db_name -q $sql")
echo '</pre>';

But please don't because it a big security issue and just considered bad.

Again, this answer depends on how specific you are defining "How MySQL does it" and "easy".

Highly suggest using something like what was mentioned in a very similar question: Print table data mysql php

or what @deceze mentioned, although using sprintf is not very flexible, it will get the job done.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号