問題描述
我正在編寫一個快速而骯臟的報告腳本,用于查詢報告并通過電子郵件發送結果.使用 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 查詢的結果,就好像它是從控制臺運行一樣的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!