Chartjs-How to load mysql query to chartjs with php?

0👍

It is better you first set the value of $p array in a javascript array in index.php and then use it in main.js.
for instance:

<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'] . '",';}?>
      ]
    }

notice: main.js files must be called after indx.php

Leave a comment