格式化MySQL查询的结果,就像从控制台运行一样 [英] Formatting the results of a MySQL query as if it were run from the console

查看:616
本文介绍了格式化MySQL查询的结果,就像从控制台运行一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个快速而肮脏的报告脚本来查询报告并通过电子邮件发送结果。当使用MySQL控制台时,结果是格式良好的表格:

  mysql>从用户中选择* 
+ ----------- + ------------ + ------- +
|名字|城市| zip |
+ ----------- + ------------ + ------- +
|玛丽亚|荷兰| 12345 |
| Rene | Doylestown | 65432 |
|海伦|康威| 98745 |
+ ----------- + ------------ + ------- +
3行(0.01秒)

使用PHP获取结果时,是否有一种简单的方法来复制这种格式?很明显,我可以通过编写自己的报告格式化程序来实现这一目标,但是我希望有更多更优雅的东西。

解决方案

您可以使用 Console_Table PEAR包。只需循环你的MySQL结果,并添加行到你的表。您可以使用 Console_Table :: setHeaders()方法为您的列添加标题,然后使用 Console_Table :: addRow()方法添加每一行,最后 Console_Table :: getTable()来显示它。



没有内置到PHP来做到这一点。如果您不想使用/编写代码来绘制控制台表,只需通过PHP将 -e query 传递给mysql,使用 passthru() code>。这将使查询终止于; \ G

  passthru(mysql -e'$ query;'database_name); 


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)

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.

解决方案

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.

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查询的结果,就像从控制台运行一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆