如何使用数据库中的数据使我的chart.js动态化

时间:2019-02-06 12:54:09

标签: javascript php chart.js

我知道这几乎是两个问题,但是我不知道该如何单独问这些问题。

  1. 如何将我的数据编辑为数据库中的数据。
  2. 如何编辑我的代码,使其在时间间隔上更新。

这是我的代码:(我试图缩短代码)

<canvas id="myChart"></canvas>
<?php foreach($csv->getHoejde1() as $csvmaal) { ?>
  <tr>
    <td><?= $csvmaal->Actual; ?></td> // This is the data for the chart
  </tr>
<?php } ?>

使用var_dump();

var_dump($csvmaal->Actual);

结果string(6) "129.74"

chart.js的脚本(使用虚拟数据)

<script src="./assets/charts/dist/Chart.js"></script>
<script>
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");

var horizonalLinePlugin = {
  afterDraw: function(chartInstance) {
    var yScale = chartInstance.scales["y-axis-0"];
    var canvas = chartInstance.chart;
    var ctx = canvas.ctx;
    var index;
    var line;
    var style;

    if (chartInstance.options.horizontalLine) {
      for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
        line = chartInstance.options.horizontalLine[index];

        if (!line.style) {
          style = "rgba(169,169,169, .6)";
        } else {
          style = line.style;
        }

        if (line.y) {
          yValue = yScale.getPixelForValue(line.y);
        } else {
          yValue = 0;
        }

        ctx.lineWidth = 3;

        if (yValue) {
          ctx.beginPath();
          ctx.moveTo(0, yValue);
          ctx.lineTo(canvas.width, yValue);
          ctx.strokeStyle = style;
          ctx.stroke();
        }

        if (line.text) {
          ctx.fillStyle = style;
          ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
        }
      }
      return;
    };
  }
};
Chart.pluginService.register(horizonalLinePlugin);

var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: "My First dataset",
    fill: false,
    lineTension: 0,
    backgroundColor: "rgba(75,192,192,0.4)",
    borderColor: "rgba(75,192,192,1)",
    borderCapStyle: 'butt',
    borderDash: [],
    borderDashOffset: 0.0,
    borderJoinStyle: 'miter',
    pointBorderColor: "rgba(75,192,192,1)",
    pointBackgroundColor: "#fff",
    pointBorderWidth: 1,
    pointHoverRadius: 5,
    pointHoverBackgroundColor: "rgba(75,192,192,1)",
    pointHoverBorderColor: "rgba(220,220,220,1)",
    pointHoverBorderWidth: 2,
    pointRadius: 4,
    pointHitRadius: 10,
    data: [130, 140, 120, 125, 130, 135, 140],
  }]
};

var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    "horizontalLine": [{
      "y": 140,
      "style": "rgba(255, 0, 0, .4)",
    }, {
      "y": 120,
      "style": "#00ffff",
    }]
  }
});

编辑:添加了丢失的代码: getHoejde1()

  public function getHoejde1()
{
    return $this->db->toList("SELECT * FROM `csvhoejde1`");
}

希望我的问题很清楚

仅出于信息目的,我已经阅读了https://www.chartjs.org/docs/latest/developers/updates.html,但并没有正确理解

3 个答案:

答案 0 :(得分:0)

  
      
  1. 如何将我的数据编辑为数据库中的数据。
  2.   

您应该制作一个单独的php文件以从数据库graph.php获取数据。从数据库中获取数据后,json_encode()print()

$query = "SELECT * FROM `csvhoejde1`";
$result = mysqli_query($conn, $query);
$data = array();
foreach($result as $row){
   $data[] = $row;
}
print(json_encode($data));
  
      
  1. 如何编辑我的代码,使其在时间间隔上更新。
  2.   

您可以通过ajax调用和setInteval()函数来完成此操作。

现在,在chart.js中,执行以下操作:

function init(){
   $.ajax({
       type : "get",
       url : "graph.php"
       success: function(data){
          var json = JSON.parse(data);

          //remaining of your chart code goes here, add this json to data 
       }
   });
}

setInterval(init, 5000);

其中5000表示5秒,请将其更改为您想要的任何时间。

答案 1 :(得分:0)

使用json从ajax到jquery或从php到jquery获取数据

答案 2 :(得分:0)

这是我怎么做的。

<?php
       //$sth = $db->prepare("SELECT Actual FROM `csv_1data` WHERE Name = '1) Height 130' ORDER BY FK_palle");
          // USE VALUE FROM <select><option></option></select> INSTEAD OF 1) Height 130
          $sth = $db->prepare("SELECT Actual FROM `Angle` ORDER BY Dato_ur_stillet");
          $sth->execute();
          /* Fetch all of the remaining rows in the result set */
          $result = $sth->fetchAll(PDO::FETCH_COLUMN);
          // $result = explode("@", implode(",@", $result));
          // print_r for at se resultaterne.
          echo'<pre>';
          print_r($result);
          echo'</pre>';
          $std = $db->prepare("SELECT Palle_nr FROM `Angle` ORDER BY `Dato_ur_stillet` ASC");
          $std->execute();
          /* Fetch all of the remaining rows in the result set */
          $palle = $std->fetchAll(PDO::FETCH_COLUMN);
        ?>
      <!----------------------myChart---------------------->
      <script src="./assets/charts/dist/Chart.js"></script>
    <script>



    var canvas = document.getElementById("myChart");
    var ctx = canvas.getContext("2d");

    var horizonalLinePlugin = {
      afterDraw: function(chartInstance) {
        var yScale = chartInstance.scales["y-axis-0"];
        var canvas = chartInstance.chart;
        var ctx = canvas.ctx;
        var index;
        var line;
        var style;

        if (chartInstance.options.horizontalLine) {
          for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
            line = chartInstance.options.horizontalLine[index];

            if (!line.style) {
              style = "rgba(169,169,169, .6)";
            } else {
              style = line.style;
            }

            if (line.y) {
              yValue = yScale.getPixelForValue(line.y);
            } else {
              yValue = 0;
            }

            ctx.lineWidth = 3;

            if (yValue) {
              ctx.beginPath();
              ctx.moveTo(0, yValue);
              ctx.lineTo(canvas.width, yValue);
              ctx.strokeStyle = style;
              ctx.stroke();
            }

            if (line.text) {
              ctx.fillStyle = style;
              ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
            }
          }
          return;
        };
      }
    };
    Chart.pluginService.register(horizonalLinePlugin);

    var data = {
      labels: [<?php echo join($palle, ',') ?>],
      datasets: [{
        label: "My First dataset",
        fill: false,
        lineTension: 0,
        backgroundColor: "rgba(75,192,192,0.4)",
        borderColor: "rgba(51,150,255,100.2)",
        borderCapStyle: 'butt',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'miter',
        pointBorderColor: "rgba(75,192,192,1)",
        pointBackgroundColor: "#fff",
        pointBorderWidth: 1,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: "rgba(75,192,192,1)",
        pointHoverBorderColor: "rgba(220,220,220,1)",
        pointHoverBorderWidth: 2,
        pointRadius: 2,
        pointHitRadius: 10,
        data: [<?php echo join($result, ',') ?>],
      }]
    };

    var myChart = new Chart(ctx, {
      type: 'line',
      data: data,
      options: {
        "horizontalLine": [{
          "y": 130.75,
          "style": "rgba(255, 0, 0, .4)",
        }, {
          "y": 129.1,
          "style": "#00ffff",
        }]
      }
    });
    </script>