引言
市场上目前有许多基于PHP的库都支持图表类型。 重要的方面是它们如何与我们的数据源连接,因为大多数情况下它们与某些数据库(例如mysql或sqlite)一起使用。
从数据库获取图表数据对于本文,我将从Northwind sqlite数据库中获取数据。 可以说我们喜欢显示产品类别和整体销售额的条形图。 查询如下:
select c.categoryname, sum(a.quantity) as Sales
from products b, `order details` a, categories c
where a.productid = b.productid and c.categoryid = b.categoryid
group by c.categoryid
order by c.categoryid
这将导致以下数据:
"Beverages" "9532"
"Condiments" "5298"
"Confections" "7906"
"Dairy Products" "9149"
"Grains/Cereals" "4562"
"Meat/Poultry" "4199"
"Produce" "2990"
"Seafood" "7681"
图表代码
我将使用PHP Charts Framework,该框架使用非常简单的API连接到数据库并绘制所需的图表类型。
步骤如下:
- 我们创建一个图表对象
- 设置数据SQL查询
- 设置图表属性和标签
- 获取图表输出
$p = new chartphp();
$p->data_sql = "select c.categoryname, sum(a.quantity) as Sales
from products b, `order details` a, categories c
where a.productid = b.productid and c.categoryid = b.categoryid
group by c.categoryid
order by c.categoryid";
// Line Data
$p->chart_type = "bar";
// Common Options
$p->title = "Category Sales";
$p->xlabel = "Category";
$p->ylabel = "Sales";
$out = $p->render('c1');
此代码将直接从数据库中生成数据库驱动的条形图。
看截图:
bar-db-chart.jpg在此框架中,可以使用各种图表,但简单易用。
From: https://bytes.com/topic/php/insights/961712-creating-simple-bar-chart-sql-query