如何使用php将mysql查询加载到chartjs?

时间:2019-03-01 10:17:49

标签: javascript php mysql mysqli chart.js

我需要帮助,你们能帮助我吗? 这是我的问题。我有2个文件:

  1. main.js
  2. index.php

这是 main.js 的来源:

var ctx = document.getElementById("percent-chart2").getContext("2d");
if (ctx) {
  ctx.height = 209;
  var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      datasets: [
        {
          label: "My First dataset",
          data: [<?php while ($p = mysqli_fetch_array($jumlah)) { echo '"' . $p['jumlah'] . '",';}?>],
          backgroundColor: [
            '#fa4251',
            '#00b5e9'
          ],
          hoverBackgroundColor: [
            '#fa4251',
            '#00b5e9'
          ],
          borderWidth: [
            0, 0
          ],
          hoverBorderColor: [
            'transparent',
            'transparent'
          ]
        }
      ],
      labels:
      [
       <?php while ($p = mysqli_fetch_array($severity)) { echo '"' . $p['severity'] . '",';}?>
      ]
    }

这是 index.php

<?php
$koneksi = mysqli_connect("localhost", "root", "waf", "waf");
$severity = mysqli_query($koneksi, "SELECT severity FROM severity order by severity asc");
$jumlah = mysqli_query($koneksi, "SELECT jumlah FROM severity order by severity asc");
?>

如果我从mysql运行查询,则会得到以下输出:

mysql> SELECT severity FROM severity order by severity asc;
+----------+
| severity |
+----------+
| CRITICAL |
| WARNING  |
+----------+
2 rows in set (0.00 sec)

mysql> SELECT jumlah FROM severity order by severity asc;
+--------+
| jumlah |
+--------+
|     35 |
|     35 |
+--------+
2 rows in set (0.00 sec)

当我运行php时,没有任何反应或出现,只是空白页。我该怎么办 ? (-_-“)

另一个问题,我可以从js运行mysql查询吗?

谢谢..

1 个答案:

答案 0 :(得分:0)

最好先在index.php的javascript数组中设置$ p数组的值,然后在main.js中使用它。 例如:

<script>
    var fields= [<?php  while ($p = mysqli_fetch_array($jumlah)) { echo '"' . $p['jumlah'] . '",';} ?>];
</script>
<?php
$koneksi = mysqli_connect("localhost", "root", "waf", "waf");
$severity = mysqli_query($koneksi, "SELECT severity FROM severity order by severity asc");
$jumlah = mysqli_query($koneksi, "SELECT jumlah FROM severity order by severity asc");
?>

main.js

var ctx = document.getElementById("percent-chart2").getContext("2d");
if (ctx) {
  ctx.height = 209;
  var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      datasets: [
        {
          label: "My First dataset",
          data: fields,
          backgroundColor: [
            '#fa4251',
            '#00b5e9'
          ],
          hoverBackgroundColor: [
            '#fa4251',
            '#00b5e9'
          ],
          borderWidth: [
            0, 0
          ],
          hoverBorderColor: [
            'transparent',
            'transparent'
          ]
        }
      ],
      labels:
      [
       <?php while ($p = mysqli_fetch_array($severity)) { echo '"' . $p['severity'] . '",';}?>
      ]
    }

注意:indx.php之后必须调用main.js文件