谷歌饼图动态与MySQL和PHP

时间:2012-10-16 11:31:55

标签: php mysql google-visualization

我想用提供的库来动态生成谷歌饼图。

我有从mysql获取数据的代码:

$query = "SELECT name FROM mybase WHERE name = '$name' ";

        $mysqli = new mysqli();
        $mysqli->connect('localhost', 'blabla', 'blabla', 'blabla');
        $result = $mysqli->query($query);
        while ($row = $result->fetch_assoc()) {
            //here I cant figure out how to make data in format for pie chart
        }

我需要将此数据提供给Java脚本。看x次表示列出数据库的次数:

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Name', 'Seen x times'],
          ['somenamefrommysql',     11],
          ['somenamefrommysql',      2],
          ['somenamefrommysql',  2],
          ['somenamefrommysql', 2],
          ['somenamefrommysql',    7]
        ]);

        var options = {
          title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

可以使用纯JSON创建DataTable,因此如果您可以让PHP脚本以其所需的格式将结果作为JSON对象返回,那么它将起作用。

请参阅https://developers.google.com/chart/interactive/docs/reference#DataTable