多线谷歌折线图,使用来自 mySQL db 的数据

Posted

技术标签:

【中文标题】多线谷歌折线图,使用来自 mySQL db 的数据【英文标题】:Multi line Google Line Chart, using data from mySQL db 【发布时间】:2017-09-05 13:46:04 【问题描述】:

我正在经历一些学习过程,以便为我的公司创建一个小型数据库支持的报告系统。

目的是使用谷歌图表绘制多折线图,基于mysql数据库。

我已经设法从 mysql 数据库中获取要回显的数据,但它没有生成图表。我得到的只是回声,以及图表应该所在的空白区域。显示回显是出于调试目的。

代码如下:

<?php include 'confile.php';

$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-03-02' ORDER BY time ASC";
$result = $conn->query($qry);

if($result === FALSE) 
    echo mysql_errno($result) .": ". mysql_error($result) ."/n";
    die(mysql_error());


$rows = array();
$table = array();
$table['cols'] = array(
                        array('label' => 'Time', 'type' => 'datetime'),
                        array('label' => 'Probe 1', 'type' => 'number'),
                        array('label' => 'Probe 2', 'type' => 'number'),
                        array('label' => 'Probe 3', 'type' => 'number'),
                        array('label' => 'Probe 4', 'type' => 'number')
                        );

while($r = mysqli_fetch_assoc($result)) 

    $temp = array();
    $temp[] = array($r['time']);

    $temp[] = array($r['p1']);
    $temp[] = array($r['p2']);              
    $temp[] = array($r['p3']);
    $temp[] = array($r['p4']);

    $rows[] = array('c' => $temp);  


$table['rows'] = $rows;

$jsonTable = json_encode($table);
echo $jsonTable;
?>
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></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.charts.load('current', 'packages':['corechart']);
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() 

        var data = new google.visualization.DataTable(<?$jsonTable?>);
        var options = 
            title: 'Recorded Temperatures',
            legend: position: 'bottom' ,
            width: 800,
            height: 600
        ; 

        var chart = new google.visualization.Table(document.getElementById('curve_chart'));
        chart.draw(data, options);  
      

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

这是“回声”输出

"cols":["label":"Time","type":"datetime","label":"Probe 1","type":"number","label":"Probe 2","type":"number","label":"Probe 3","type":"number","label":"Probe 4","type":"number"],"rows":["c":[["03:02:07"],["270.26"],["298.40"],["111.54"],["228.06"]],"c":[["03:28:42"],["273.23"],["190.43"],["245.69"],["283.21"]],"c":[["07:26:04"],["144.33"],["217.26"],["206.53"],["167.68"]],"c":[["12:13:20"],["153.15"],["277.23"],["167.20"],["240.88"]]]

这是测试数据,在 db 上使用测试查询。一旦我了解了呈现图表的格式,它将被设置为允许用户选择查看哪个日期等。

这是我能找到的最接近的现有问题,但似乎没有回答这个问题。

Not able to generate a Google Chart using MySQL table data as the data source


按照@MickMackusa 的回答,我设法通过确保 mysql/php 数组以 Google Charts 可接受的方式输出来将其组合在一起以使其正常工作。

感谢@MickMacUSA 的帮助。

最终的工作代码如下。

<?php include 'confile.php';

$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-04-16' ORDER BY time ASC";
$result = $conn->query($qry);

if($result === FALSE) 
    echo mysqli_errno($result) .": ". mysqli_error($result) ."/n";
    die(mysqli_error());

    $i = 0; //iteration counter - start at 0

    $totalRows = mysqli_num_rows($result); // we need this to know when to change the output
    $targetRows = $totalRows - 1; //row indies start from 0, not 1.

    foreach ($result as $row) 

        $comTime = str_replace(":",",",$row['time']); // for each row, remove the : and put , in its place
        if ($targetRows == $i)  // if the index is the same value as the target (ie, it's the last row)...

            $temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."]". PHP_EOL;
             else 
            $temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."],". PHP_EOL;
            
        $i = $i + 1; 
        $rows[] = $temp; 
    

 $table = $rows;
 $data = implode($table); //format the table as a single string, with line returns

//echo $i;
//echo $data;

?>
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  </head>
  <body>
    <div id="chart" style="width: 900px; height: 500px"></div>

    <script type="text/javascript">
      google.charts.load('current', 'packages':['corechart']);
      google.charts.setOnLoadCallback(drawChart);

      function drawChart()
        var data = new google.visualization.DataTable();
            data.addColumn('timeofday','Time'); 
            data.addColumn('number','Probe 1');
            data.addColumn('number','Probe 2');
            data.addColumn('number','Probe 3');
            data.addColumn('number','Probe 4');

            data.addRows([              
                <?php echo $data; ?> //dump the result into here, as it's correctly formatted   
            ]);

        var options = 
            title: 'Recorded Temperatures',
            legend:  position: 'bottom' ,
            width: 900,
            height: 500,
            hAxis:  format: 'hh:mm:ss' 
        ; 

    var chart = new google.visualization.LineChart(document.getElementById('chart'));
      chart.draw(data, options);    
      
    </script>
  </body>
</html>

【问题讨论】:

尽量不要过多地修正你的问题,否则你会抢走我的风头,我的回答中的要点就没有意义了。我想请您回滚编辑,因为您无需更正原始消息即可讲述故事 按要求回滚。 【参考方案1】:

您的数字值的格式必须不同,并且您需要timeofday 而不是datetime

根据:https://developers.google.com/chart/interactive/docs/reference#dataparam

将您的数据格式化为如下所示:

cols:
    [
        "label":"Time","type":"timeofday",
        "label":"Probe 1","type":"number",
        "label":"Probe 2","type":"number",
        "label":"Probe 3","type":"number",
        "label":"Probe 4","type":"number"
    ],
rows:
    [
        c:[v:[03,02,07],f:'03:02:07',v:270.26,v:298.40,v:111.54,v:228.06],
        c:[v:[03,28,42],f:'03:28:42',v:273.23,v:190.43,v:245.69,v:283.21],
        c:[v:[07,26,04],f:'07:26:04',v:144.33,v:217.26,v:206.53,v:167.68],
        c:[v:[12,13,20],f:'12:13:20',v:153.15,v:277.23,v:167.20,v:240.88]
    ]

而且你必须在 javascript 中回显它:

改变:

<?$jsonTable?>

到:

<?php echo $jsonTable; ?>  

并将您的 javascript 代码块放在您的 &lt;/body&gt; 标记之前。

这是我在服务器上测试的使用上述数据格式的完整工作代码:

<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>

    <script type="text/javascript">
    google.charts.load('current', 'packages':['corechart']);
    google.charts.setOnLoadCallback(drawChart);

    function drawChart()
        var data = new google.visualization.DataTable(
            cols:[
                "label":"Time","type":"timeofday",
                "label":"Probe 1","type":"number",
                "label":"Probe 2","type":"number",
                "label":"Probe 3","type":"number",
                "label":"Probe 4","type":"number"
            ],
            rows:[
                c:[v:[03,02,07],f:'03:02:07',v:270.26,v:298.40,v:111.54,v:228.06],
                c:[v:[03,28,42],f:'03:28:42',v:273.23,v:190.43,v:245.69,v:283.21],
                c:[v:[07,26,04],f:'07:26:04',v:144.33,v:217.26,v:206.53,v:167.68],
                c:[v:[12,13,20],f:'12:13:20',v:153.15,v:277.23,v:167.20,v:240.88]
            ]
        );

        var options = 
            title: 'Recorded Temperatures',
            legend:  position: 'bottom' ,
            width: 900,
            height: 500,
            hAxis:  format: 'hh:mm:ss' 
        ;

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
        chart.draw(data, options);   
    
    </script>
</body>
</html>

这是一种替代格式,使用 mysqli 结果将更简单/更清晰/更容易构建/理解:

<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>

    <script type="text/javascript">
    google.charts.load('current', 'packages':['corechart']);
    google.charts.setOnLoadCallback(drawChart);

    function drawChart()
        var data = new google.visualization.DataTable();
            data.addColumn('timeofday','Time');
            data.addColumn('number','Probe 1');
            data.addColumn('number','Probe 2');
            data.addColumn('number','Probe 3');
            data.addColumn('number','Probe 4');
        data.addRows([
            [[03,02,07],270.26,298.40,111.54,228.06],
            [[03,28,42],273.23,190.43,245.69,283.21],
            [[07,26,04],144.33,217.26,206.53,167.68],
            [[12,13,20],153.15,277.23,167.20,240.88]
        ]);

        var options = 
            title: 'Recorded Temperatures',
            legend:  position: 'bottom' ,
            width: 900,
            height: 500,
            hAxis:  format: 'hh:mm:ss' 
        ;

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
        chart.draw(data, options);   
    
    </script>
</body>
</html>

查看WhiteHat提供的SO Demo:

google.charts.load('current', 
  callback: drawChart,
  packages: ['corechart', 'table']
);

function drawChart() 
  var data = new google.visualization.DataTable(cols: [
      "label":"Time","type":"timeofday",
      "label":"Probe 1","type":"number",
      "label":"Probe 2","type":"number",
      "label":"Probe 3","type":"number",
      "label":"Probe 4","type":"number"
    ],
    rows: [
      c:[v:[03,02,07],f:'03:02:07',v:270.26,v:298.40,v:111.54,v:228.06],
      c:[v:[03,28,42],f:'03:28:42',v:273.23,v:190.43,v:245.69,v:283.21],
      c:[v:[07,26,04],f:'07:26:04',v:144.33,v:217.26,v:206.53,v:167.68],
      c:[v:[12,13,20],f:'12:13:20',v:153.15,v:277.23,v:167.20,v:240.88]
    ]
  );

  var table = new google.visualization.Table(document.getElementById('chart_0'));
  table.draw(data);

  var options = 
      title: 'Recorded Temperatures',
      legend: position: 'bottom' ,
      width: 800,
      height: 600,
      hAxis: 
        format: 'hh:mm:ss'
      
  ;
  var chart = new google.visualization.LineChart(document.getElementById('chart_1'));
  chart.draw(data, options);
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_0"></div>
<div id="chart_1"></div>

【讨论】:

@StevenDavison 在 javascript 中实现我建议的回显后,您的 json 是否显示在页面的源代码中?请确认。 json数据总是通过echo $jsonTable展示出来的;在第 38 行。不再重复。 它并没有从代码的 javascript 部分回显,但我不希望它是,因为它是作为 Google 图表的数据传递的。 啊哈,我明白了。是的,它正在被回应。 对我来说看起来不错 -- 在问题中也注意到 -- 正在使用 Table 图表,但尚未加载 'table' 包 --> var chart = new google.visualization.Table

以上是关于多线谷歌折线图,使用来自 mySQL db 的数据的主要内容,如果未能解决你的问题,请参考以下文章

我无法使用 mysql 表中的数据创建谷歌折线图

谷歌折线图双Y轴问题

如何修改谷歌折线图的JSON字符串

谷歌折线图显示负值

如何更改用于谷歌折线图的数据结构

用单值显示谷歌折线图