使用SQL查询创建简单的条形图

引言

市场上目前有许多基于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连接到数据库并绘制所需的图表类型。

步骤如下:

  1. 我们创建一个图表对象
  2. 设置数据SQL查询
  3. 设置图表属性和标签
  4. 获取图表输出

$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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值