我正在努力从MySql表创建一个饼图。
我的表格如下
buy_trader qty
TKS3G 2069
MSB1G 4417
JKB6 4021
FWS2 3507
ASI1G 2578
other 18228
我正在使用以下代码从表中生成饼图。请帮帮我这个
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("offlinesurv", $con);
$result = mysql_query("SELECT * FROM top_buy_trades");
while($row = mysql_fetch_array($result)) {
echo $row['buy_trader'] . "\t" . $row['qty']. "\n";
}
mysql_close($con);
?>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Top Buy Traders'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: 'green',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Broker share',
data: [<?php echo $row ?>]
}]
});
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
请帮我解决这个问题。有一段时间我正在努力解决这个问题。
这段代码中的错误是
答案 0 :(得分:0)
这一行:
data: [<?php echo $row ?>]
不在循环中。您需要通过循环遍历整个数据库结果,从mysql数据生成highcahrts的一系列数据。此时将生成一行,并且因为它在PHP循环之外,所以它将是不正确的。
它应该是这样的:
while($row = mysql_fetch_array($result)) {
echo //more data into your series array into the JS code
}
答案 1 :(得分:0)
您无法传递这样的值。请尝试以下代码,
将while循环更改为,
while($row = mysql_fetch_array($result)) {
$traders[] = array(
'trader' => $row['buy_trader'],
'qty' => $row['qty']
);
}
然后将脚本更改为
series: [{
type: 'pie',
name: 'Broker share',
data: [
<?php
foreach($traders as $trader) {
echo "[".$trader['trader'].",". $trader['qty']."],";
}
?>
]
}]
答案 2 :(得分:0)