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

问题描述 投票:1回答:3

我知道这是一个相当多的2个问题,但我不知道我应该如何单独提问。

  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但没有正确理解

javascript php chart.js
3个回答
0
投票

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


0
投票
  1. 如何将数据编辑为数据库中的数据。

你应该制作一个单独的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. 如何编辑我的代码,以便它按时间间隔更新。

您可以使用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秒,将其更改为您想要的任何时间。


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>
© www.soinside.com 2019 - 2024. All rights reserved.