使用PHP和谷歌图表从MySQL数据库创建饼图字符 [英] Creating Pie char from mysql database using php and google charts
问题描述
temp - > 我试图为我的数据库表创建一个馅饼字符。列(id,sent,pcount,ncount)
pcount
和 ncount
是int数字。我想为这两个值创建一个饼图。
我试图加载这个文件。
< HTML>
< head>
< script type =text / javascriptsrc =https://www.google.com/jsapi>< / script>
< script type =text / javascriptsrc =http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js>< / script>
< script type =text / javascript>
google.load(visualization,1,{packages:[corechart]});
google.setOnLoadCallback(drawChart);
$ b函数drawChart()
{
var jsonData = $ .ajax({
url:graphData.php,
dataType:json ,
async:false
})。responseText;
//从服务器加载的JSON数据中创建我们的数据表。
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales',
'width':500,
'height':400};
//实例化并绘制我们的图表,并传入一些选项。
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
< / script>
< / head>
< body>
<! - 将存放饼图的Div - >
< div id =chart_div>< / div>
< / body>
< / html>
graphData.php的内容如下。
< pre $
<?php
$ con = mysqli_connect('127.0.0.1:3306','root','root','test');
if(mysqli_connect_errno()){
echo无法连接到MySQL:.mysqli_connect_error();
}
$ sql =选择pcount,count(*)从temp计数;
$ b $ if($ result = mysqli_query($ con,$ sql))
{
$ rownum = mysqli_num_rows($ result);
printf(Result set has%d rows.\\\
,$ rownum);
mysqli_free_result($ result);
//以Google Chart js / API预期的格式启动json数据
$ data = array('cols'=> array(array( 'label'=>'pcount','type'=>'int'),
array('label'=>'mcount','type'=>'int')),
'rows'=> array());
$ b $ while($ row = mysqli_fetch_row($ result)){
$ data ['rows'] [] = array('c'=> array(array('v'= > $ row [0]),array('v'=> $ row [1])));
}
echo json_encode($ data);
?>
我从web上取得了这段代码并根据需要进行了修改。当我加载我的第一个PHP页面时,它什么都没显示。我做错了什么?
这是创建PIE图表的代码(只需更改其他图表的函数名称)
重要的是要记住的是
数组('label'=>'ind_type','type'=>'string'),
array('label'=>'sum','type'=>'number')
ind_type和sum是我表中的列,第一个var应该是字符串。
<?php
/ *
脚本:PHP-JSON-MySQLi-GoogleChart
作者:Enam Hossain
版本:1.0
* /
/ *
-------------- -------------------------------------------------- ----
用法:
------------------------------------ --------------------------------
要求:PHP,Apache和MySQL
安装:
---使用phpMyAdmin创建数据库并将其命名为图表
---使用phpMyAdmin创建一个表并将其命名为googlechart和确保表格只有两列,因为我已经使用了两列。但是,如果您愿意,您可以使用多于2列,但是您必须为该
更改一些代码---指定列名称如下:weekly_task和percentage
- - 将一些数据插入表中
---对于百分比列只使用一个数字
-------------------- -------------
示例数据:表(googlechart)
---------------------- -----------
weekly_task百分比
----------- ----------
睡眠30
看电影10
工作40
练习20
* /
/ *建立数据库连接* /
// $ mysqli = new mysqli_connect('127.0.0.1:3306','root','root','test');如果(mysqli_connect_errno()){
printf(连接失败:%s \ n,mysqli_connect_error());
$ b $ *
exit();
} * /
$ mysqli = mysqli_connect('127.0.0.1:3306','root','root','test');
if(mysqli_connect_errno()){
echo无法连接到MySQL:.mysqli_connect_error();
从表中选择所有的每周任务googlechart * /
$ result = $ mysqli-> query('SELECT * FROM new_temp');
/ *
---------------------------
示例数据:表( googlechart)
--------------------------
Weekly_Task百分比
睡眠30
观看电影10
job 40
练习20
* /
$ rows = array();
$ table = array();
$ table ['cols'] =数组(
)//你的图表的标签,它们代表列标题
/ *
注意一列是以字符串格式显示,另一个显示为数字格式
作为饼图只需要数字来计算百分比
并且字符串将用于切片标题
* /
array('label'=>'ind_type','type'=>'string'),
array('label'=>'sum','type'=> 'number')
);
/ *从$ result * /
foreach($ result as $ r)中提取信息{
$ temp = array();
//下面一行将用于分割饼图
$ temp [] = array('v'=>(string)$ r ['ind_type ]);
//每个切片的值
$ temp [] = array('v'=>(int)$ r ['sum']);
$ rows [] = array('c'=> $ temp);
}
$表['rows'] = $ rows;
//将数据转换为JSON格式
$ jsonTable = json_encode($ table);
// echo $ jsonTable;
?>
< html>
< head>
<! - 加载Ajax API - >
< script type =text / javascriptsrc =https://www.google.com/jsapi>< / script>
< script type =text / javascriptsrc =http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js>< / script>
< script type =text / javascript>
//加载可视化API和饼图包。
google.load('visualization','1',{'packages':['corechart']});
//设置回调以在加载Google Visualization API时运行。
google.setOnLoadCallback(drawChart);
函数drawChart(){
//从服务器加载的JSON数据中创建我们的数据表。
var data = new google.visualization.DataTable(<?= $ jsonTable?>);
var options = {
title:'Index analysis',
is3D:'true',
width:800,
height:600
};
//实例化并绘制我们的图表,并传入一些选项。
//不要忘记检查你的div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
< / script>
< / head>
< body>
<! - 这是容纳饼图的div - >
< div id =chart_div>< / div>
< / body>
< / html>
I am trying to create a pie char for my database table.
temp -> with columns(id, sent, pcount, ncount)
pcount
and ncount
are int numbers. I want to create a pie chart for this two values.
I am trying to load this file.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var jsonData = $.ajax({
url: "graphData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
graphData.php content is the following.
<?php
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$sql = "SELECT pcount,count(*) AS count from temp";
if ($result=mysqli_query($con,$sql))
{
$rownum=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rownum);
mysqli_free_result($result);
}
//start the json data in the format Google Chart js/API expects to receieve it
$data = array('cols' => array(array('label' => 'pcount', 'type' => 'int'),
array('label' => 'mcount', 'type' => 'int')),
'rows' => array());
while($row = mysqli_fetch_row($result)) {
$data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
echo json_encode($data);
?>
I have taken this code from web and modified as per my need. When I load my first PHP page, it shows nothing. What am I doing wrong?
Here is the code to create PIE chart(Just change function name for other charts) from my sql table in PHP.
Important thing to remember is
array('label' => 'ind_type', 'type' => 'string'),
array('label' => 'sum', 'type' => 'number')
ind_type and sum are the column in my table, first var should be string here.
<?php
/*
Script : PHP-JSON-MySQLi-GoogleChart
Author : Enam Hossain
version : 1.0
*/
/*
--------------------------------------------------------------------
Usage:
--------------------------------------------------------------------
Requirements: PHP, Apache and MySQL
Installation:
--- Create a database by using phpMyAdmin and name it "chart"
--- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
--- Specify column names as follows: "weekly_task" and "percentage"
--- Insert some data into the table
--- For the percentage column only use a number
---------------------------------
example data: Table (googlechart)
---------------------------------
weekly_task percentage
----------- ----------
Sleep 30
Watching Movie 10
job 40
Exercise 20
*/
/* Establish the database connection */
// $mysqli = new mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
/* if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} */
$mysqli =mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
/* select all the weekly tasks from the table googlechart */
$result = $mysqli->query('SELECT * FROM new_temp');
/*
---------------------------
example data: Table (googlechart)
--------------------------
Weekly_Task percentage
Sleep 30
Watching Movie 10
job 40
Exercise 20
*/
$rows = array();
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles.
/*
note that one column is in "string" format and another one is in "number" format
as pie chart only required "numbers" for calculating percentage
and string will be used for Slice title
*/
array('label' => 'ind_type', 'type' => 'string'),
array('label' => 'sum', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['ind_type']);
// Values of the each slice
$temp[] = array('v' => (int) $r['sum']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'Index analysis',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
这篇关于使用PHP和谷歌图表从MySQL数据库创建饼图字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!