Formatting the results of a MySQL query as if it were run from the console(格式化 MySQL 查询的结果,就好像它是从控制台运行一样)
问题描述
我正在编写一个快速而肮脏的报告脚本,用于查询报告并通过电子邮件发送结果.使用 MySQL 控制台时,结果显示在格式良好的表格中:
I'm writing a quick and dirty reporting script that queries a report and emails the results. When using the MySQL console the results are in a nicely formatted table:
mysql> select * from users;
+-----------+------------+-------+
| firstname | city | zip |
+-----------+------------+-------+
| Maria | Holland | 12345 |
| Rene | Doylestown | 65432 |
| Helen | Conway | 98745 |
+-----------+------------+-------+
3 rows in set (0.01 sec)
在使用 PHP 获取结果时,是否有一种简单的方法可以复制这种格式?显然,我可以通过编写自己的报告格式化程序来实现这一点,但我希望有一些更优雅的东西.
Is there an easy way to replicate this formatting when fetching the results with PHP? Obviously I could achieve this by writing my own report formatter but I was hoping for something a little more elegant.
推荐答案
您可以使用 轻松完成此操作Console_Table PEAR 包.只需遍历您的 MySQL 结果,并将行添加到您的表中.您可以使用 Console_Table::setHeaders()
方法为您的列添加标题,然后使用 Console_Table::addRow()
方法添加每一行,最后 Console_Table::getTable()
显示它.
You could do this quite easily using the Console_Table PEAR package. Just loop through your MySQL results, and add rows to your table. You can use the Console_Table::setHeaders()
method to add the headers for your columns, then the Console_Table::addRow()
method to add each row, and finally Console_Table::getTable()
to display it.
PHP 没有内置任何东西来做到这一点.如果您不想使用/编写代码来绘制控制台表,只需使用 passthru()
通过 PHP 将 -e query
传递给 mysql.这将工作以 ;
和 G
终止的查询:
There is nothing built into PHP to do this. If you don't want to use/write code to draw console tables, just pass -e query
to mysql via PHP using passthru()
. This will work queries terminated with both ;
and G
:
passthru("mysql -e '$query;' database_name");
这篇关于格式化 MySQL 查询的结果,就好像它是从控制台运行一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:格式化 MySQL 查询的结果,就好像它是从控制台运行一样
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01