首页 > 解决方案 > 尝试使用 mysql 表和 PHP 绘制谷歌图表时出现“无法读取未定义的属性 'datefield'”

问题描述

我尝试使用 PHP 从数据库表中检索的值创建 google 图表,我的数据库已连接,但出现类似“无法读取未定义的属性 'datefield'”的错误

我的数据库表包含两列'Row Labels (VARCHAR)', 'Sum of No in Rows (INT)'。我不明白为什么会出现这个错误。

<?php
$connection = mysqli_connect('localhost', 'root', '', 'testingoforiginal');
$result = mysqli_query($connection, "SELECT * FROM ba");
if($result){
   echo "CONNECTED";
}
?>
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['bar']});
      google.charts.setOnLoadCallback(drawStuff);

      function drawStuff() {
        var data = new google.visualization.arrayToDataTable([
          ['Row Labels', 'Sum of No in Rows'],
          <?php
              if(mysqli_num_rows($result) > 0 ){
                  while($row = mysqli_fetch_array($result)){
                      echo"['".$row['Row Labels']."',[".$row['Sum of No in Rows']."]],";

                  }
              }
          ?>
        ]);

        var options = {
          title: 'BA',
          width: 900,
          legend: { position: 'none' },
          chart: { title: 'BA',
                   subtitle: ' ' },
          bars: 'horizontal', // Required for Material Bar Charts.
          axes: {
            x: {
              0: { side: 'top', label: 'Sum of No in Rows'} // Top x-axis.
            }
          },
          bar: { groupWidth: "90%" }
        };

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

标签: javascriptphpchartsgoogle-visualization

解决方案


尝试删除第二行值中的额外括号...

改变...

echo"['".$row['Row Labels']."',[".$row['Sum of No in Rows']."]],";

至...

echo"['".$row['Row Labels']."',".$row['Sum of No in Rows']."],";

编辑

推荐使用json_encode从 php 传递 json 数据。

在 php 中构建你的数组...

<?php
  $connection = mysqli_connect('localhost', 'root', '', 'testingoforiginal');
  $result = mysqli_query($connection, "SELECT * FROM ba");
  if($result){
    echo "CONNECTED";
  }

  $data = array();
  $data[] = ['Row Labels', 'Sum of No in Rows'];
  if(mysqli_num_rows($result) > 0 ){
    while($row = mysqli_fetch_array($result)) {
      $data[] = [$row['Row Labels'], $row['Sum of No in Rows']];
    }
  }
?>

然后在页面上对其进行编码以创建数据表...

var data = new google.visualization.arrayToDataTable(<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>);

推荐阅读