使用谷歌图表API在PHP中实现图形

时间:2012-09-03 10:36:32

标签: php graph visualization google-visualization

我想要一个简单的脚本/库,通过它我可以绘制简单的图形,如line,column,pie等。 没有ajax,json,flash请... 我已经尝试过pChart,amCharts但面对其中的一些或其他问题...使用谷歌可视化api ...发现它很好但无法将数据从我的mysql数据库提供给图表 我的代码如下:

<?php 
include('dbconnect.php');
$sql_data = mysql_query("SELECT date , value FROM table1 WHERE   
                               value ='xyz' ORDER BY date DESC");
?> 
<html>
 <head>
 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <?php echo "<script type=text/javascript>";
    echo "google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});";
    echo "google.setOnLoadCallback(drawChart);";
    echo "function drawChart() { ";
    echo "var data = google.visualization.arrayToDataTable([
    ['Date', 'Score'],";
    while($result = mysql_fetch_array($sql_data))
    {
    echo "[".$result['date'] .",".$result['value']."]";
    }
    echo " ]);";

    echo "var options = {
      title: 'Score  Analysis'
    };";

    echo "var chart = new google.visualization.LineChart(document.getElementById('chart_div'));";
    echo "chart.draw(data, options);";
  echo "}
</script>";

?>
  </head>
  <body>
   <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
  </html>

1 个答案:

答案 0 :(得分:0)

除了最后一行之外,每行数据后面都需要一个逗号。不要像你一样回应,而是将结果设置为变量......

$display .= "[".$result['date'] .",".$result['value']."],";

当循环结束时,尾随逗号:

 $display .= substr($display, 0, -1);

然后

echo $display;

查看谷歌排行榜的游乐场:

http://code.google.com/apis/ajax/playground/?type=visualization#line_chart