感谢mbelton。我的代码现在运行良好,我还修改了以下代码。
我正在尝试使用Google饼图来执行销售年度。首先我有HTML文件,让用户选择他们想要审查的年份;其次,基于$ year选择,我编写PHP连接到mysql以获取相关的销售数据;第三,我创建了一个pieData表来存储String Quarter和double sales number;然后JavaScript获取饼图char。我运行代码没有显示任何错误,但我没有看到饼图出现。请有人告诉我在哪里修改使它工作?感谢。
$year = $_POST['year'];
$mysqli = mysqli_connect("root", "account", "passwd", "testDB")
or die(mysqli_error());
$query = "SELECT Q1,Q2,Q3,Q4 from sales where year LIKE '$year'";
$result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
/*get the values of each quarter, and store in new table:pieData.
* if user choose year of 2012, then the new table should look like:
* Quarter Number
* ------------------
* Q1 127.24
* Q2 106.54
* Q3 88.04
* Q4 120.89
*/
while ($info = mysqli_fetch_array($result)) {
$Q1 = $info['Q1'];
$Q2 = $info['Q2'];
$Q3 = $info['Q3'];
$Q4 = $info['Q4'];
}
$pieData = array(
array('Quarter', 'Number'),
array('Q1', (double)$Q1),
array('Q2', (double)$Q2),
array('Q3', (double)$Q3),
array('Q4', (double)$Q4)
);
$jsonTable = json_encode($pieData);
<script type="text/javascript" src="http://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 package
google.load("visualization", "1", {packages: ["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable(
<?php echo $jsonTable; ?>
);
var options = {
title:"Sales Pie"
};
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById("piechart"));
chart.draw(data, options);
}
</script>
答案 0 :(得分:0)
我认为您的代码中的错误在于打开/关闭<script
标记,在.arrayToDataTable
中您需要删除方括号[]
将代码更改为:
<?php
$Q1 = 127.24;
$Q2 = 106.54;
$Q3 = 88.04;
$Q4 = 120.89;
$pieData = array(
array('Quarter', 'Number'),
array('Q1', (double)$Q1),
array('Q2', (double)$Q2),
array('Q3', (double)$Q3),
array('Q4', (double)$Q4)
);
$jsonTable = json_encode($pieData);
?>
<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.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(
<?php echo $jsonTable; ?>
);
var options = {
title: "My Daily Activities"
};
var chart = new google.visualization.PieChart(document.getElementById("piechart"));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>