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

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

我需要帮助,你们能帮助我吗?这是我的问题。我有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吗?

谢谢..

javascript php mysql mysqli chart.js
1个回答
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'] . '",';}?>
      ]
    }

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

© www.soinside.com 2019 - 2024. All rights reserved.