如何使用来自mySQL数据库的数据填充Google折线图。 (单个文件/内联解决方案)

时间:2018-12-17 11:33:15

标签: mysql charts google-visualization flatpickr

我有一个带温度和湿度传感器的MCU(ESP8266)。 MCU通过MQTT将测量数据发送到运行在Synology NAS上的MQTT代理。 MQTT客户端(Node.js)也在NAS上运行,该客户端将接收到的数据写入NAS上的MySQL数据库。 最后但并非最不重要的一点是,网络服务器和PHP服务器也在NAS上运行。

现在,我想建立一个网站,以折线图的形式显示数据库中的数据。

  

问题:

     
      
  • 如何用mySQL数据库中的数据填充Google折线图?
  •   
  • 是否可以使用一个文件(.php)来执行此操作?
  •   
  • 如何管理日期范围选择?
  •   
  • 如何选择/取消选择图表上的线?
  •   

1 个答案:

答案 0 :(得分:-1)

这是我对问题的回答。

由于我对所使用的编程语言没有太大的了解,因此我不得不在网络上搜索,阅读和测试许多资源,才能将结果复制在一起:-) 以后我会对其进行扩展,但是对我来说,它运行良好。

我想在这里介绍这个解决方案,以帮助其他人入门。 但是,肯定有很多方法可以改进代码。 如果有人愿意,我很乐意提供建议。 在Github上完成文件。 https://github.com/DIYDave/MySQL-and-Google-Line-Chart

  1. PHP。从数据库读取数据,然后向javascript返回JSON字符串
<?php
function getData(){
 // Connect to MySQL (db Hostname/IP, user, password, database)
    $link = new mysqli( '192.168.10.10', 'user', 'password', 'mymqttdb' );
    if ( $link->connect_errno ) {
        die( "Failed to connect to MySQL: (" . $link->connect_errno . ") " . $link->connect_error );
    }   
    $start = $_GET['startDate'];        // Get parameter from URL
    $ende = $_GET['endDate'];           // Get parameter from URL

    if (!isset($endDate )){             // No end date? then actual for end
        $endDate = date('Y-m-d H:i', time());
    }   
    if (!isset($startDate )){           // No start date? then actual -1 day for start
        $startDate = date('Y-m-d H:i', strtotime('-1 day', strtotime($ende)));
    }
    // Query in SQL ! add your own columns and database table name!
    $query= "SELECT `DateTime`,`temperature`,`humidity` FROM `Chickenhouse` WHERE `DateTime` BETWEEN" . "'" . $startDate ."'" . "AND" . "'" . $endDate ."'";
    $result = $link->query($query);     // make db query

    $rows = array();
    $table = array(); 

    $table['cols'] = array
    (
        array('label' => 'Date Time', 'type' => 'datetime'),
        array('label' => 'Temperatur (°C)', 'type' => 'number'),        // Select your label for the index
        array('label' => 'Luftfeuchtigkeit (%)', 'type' => 'number')    // Select your label for the index
    ); 

    while($row = mysqli_fetch_array($result))       // got to all the lines of the query result
    {
        $sub_array = array();
        $date1 = new DateTime($row['DateTime']);
        $date2 = "Date(".date_format($date1, 'Y').", ".((int) date_format($date1, 'm') - 1).", ".date_format($date1, 'd').", ".date_format($date1, 'H').", ".date_format($date1, 'i').", ".date_format($date1, 's').")";
        $sub_array[] =  array("v" => (string)$date2);
        $sub_array[] =  array("v" => $row["temperature"]);
        $sub_array[] =  array("v" => $row["humidity"]);
        $rows[] =  array("c" => $sub_array);
    }
    $table['rows'] = $rows;
    $lineCount = count($rows);                          // Number of array fields (lines) to show in browser
    return array(json_encode($table), $lineCount);      // Make JSON from array and give it to the java script together with linecount
}
?> 
  1. CSS和HTML。或多或少只是为了格式化和设置占位符。
<html>
<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.2.3/flatpickr.css">
<style>
*{font-family:Arial;}
    .page-wrapper{ width:90%; margin:0 auto; }
    input { border: 2px solid whitesmoke;border-radius: 12px; padding: 12px 10px; text-align: center;  font-size: 16px; font-weight: bold; width: 250px;background: cornflowerblue; color: yellow;}
    button { border: none; border-radius: 10px; text-align: center; padding: 12px 10px; cursor: pointer; font-weight: bold; background: cornflowerblue; color: white;}
</style>
</head>
<body>
    <div class="page-wrapper">  </div>  
    <input type="text" style="float:left" id="rangeDate" placeholder="Select Timespan" data-input>
    <br>
    <p id="LineCount" > </p>
    <div id="line_chart" style="width: 100%; height: 800px"></div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.2.3/flatpickr.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
  1. JavaScript。 Google图表。接受JSON数据并将其显示为折线图。这里有很多选择。 此处的详细信息:https://developers.google.com/chart/interactive/docs/gallery/linechart
// Setup and show Google line chart
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
    var data = new google.visualization.DataTable(<?php echo getData()[0]?>);       //  Call PHP-Function an receive JSON
    document.getElementById("LineCount").innerHTML= "  " + <?php echo getData()[1]?> + " Records loaded";   // Get record count
    var options = {
        series: {
            0:{color: 'red', visibleInLegend: true, targetAxisIndex: 0},
            1:{color: 'blue', visibleInLegend: true, targetAxisIndex: 1}
        },
        vAxes: {
            // Adds labels to each axis; they don't have to match the axis names.
            0: {title: 'Temp (°C)' }, // , 'minValue': 0, 'maxValue': 30
            1: {title: 'Feuchte(%)'}
        },
        title:'Chickenhouse',
        legend:{position:'top'},
        chartArea:{width:'75%', height:'65%'},
        //curveType: 'function',
        hAxis: {
            title: 'Datum',  titleTextStyle: {color: '#333'},
            format: 'd.M HH:mm',
            slantedText:true, slantedTextAngle:80
        },
        explorer: { 
            actions: ['dragToPan', 'dragToZoom', 'rightClickToReset'],  // 'dragToZoom' 
            axis: 'horizontal',
            keepInBounds: true,
            maxZoomIn: 28.0,
            maxZoomOut: 1.0,
            zoomDelta: 1.5
        },
        colors: ['#D44E41'],
    };
    var date_formatter = new google.visualization.DateFormat({ // Tooltip format
    pattern: "dd.MM.yyyy -   HH:mm"
    }); 
    date_formatter.format(data, 0);
    var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
    chart.draw(data, options);
  1. Javascript。通过单击图例选择显示的行。

    // Select / deselect lines by clicking on the label
        var columns = [];
    var series = {};
    for (var i = 0; i < data.getNumberOfColumns(); i++) {
        columns.push(i);
        if (i > 0) {
            series[i - 1] = {};
        }
    }
    google.visualization.events.addListener(chart, 'select', function () {
        var sel = chart.getSelection();
        // if selection length is 0, we deselected an element
        if (sel.length > 0) {
            // if row is undefined, we clicked on the legend
            if (sel[0].row === null) {
                var col = sel[0].column;
                if (columns[col] == col) {
                    // hide the data series
                    columns[col] = {
                        label: data.getColumnLabel(col),
                        type: data.getColumnType(col),
                        calc: function () {
                            return null;
                        }
                    };
    
                    // grey out the legend entry
                    series[col - 1].color = '#CCCCCC';
                } else {
                    // show the data series
                    columns[col] = col;
                    series[col - 1].color = null;
                }
                var view = new google.visualization.DataView(data);
                view.setColumns(columns);
                chart.draw(view, options);
            }
        }
    });
    

    };

  2. Javascript。 Flatpickr。很酷的javascript应用程序,用于选择日期和时间。也可以选择我在这里使用的日期范围。 https://flatpickr.js.org/

// Flatpickr to select date range
$("#rangeDate").flatpickr({
    enableTime: false,
    mode: 'range',
    time_24hr: true,
    dateFormat: "Y-m-d",
    maxDate: "today",
    defaulDate: "today",
    onClose: function test(selectedDates, dateStr, instance){
        arDateTime = dateStr.split(" to ");
        dateTimeStart = arDateTime[0] + " 00:00" ;
        dateTimeEnd =  arDateTime[1] + " 23:59" ;
        strNeu = "?startDate=" + dateTimeStart + "&endDate=" + dateTimeEnd;
        window.location = strNeu;
    },
});

在Github上完成文件。 https://github.com/DIYDave/MySQL-and-Google-Line-Chart

结果: Screenshot