Skip to content
Advertisement

Display items from the database in a chart

I want to display the average of results for each exam paper in a graph. my problem is that when I catch the data from my database I stored it in an array so that I couldn’t print these values as a list of array such as ["a","b","c","d","e"] or [44,100,50.29,100] to use it in var xValues and var yValues , I also tried to use foreach, but it doesn’t work. Please help.

/* Here is JS code */

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<script>
    var xValues =<?php foreach($examPapertitle as $title) {
                        echo $title;
                        }; ?>
                        
    var yValues =<?php foreach($avgcountresult as $average) {
                        echo $average;
                        }; ?>
    var barColors = ["red", "green","blue","orange","brown"];

    new Chart("myChart", {
      type: "bar",
      data: {
        labels: xValues,
        datasets: [{
          backgroundColor: barColors,
          data: yValues
        }]
      },
      options: {
        legend: {display: false},
        title: {
          display: true,
          text: "Average of Results"
        }
      }
    });
</script>

/* Here is HTML Code */

$examPapertitle=array();
$avgcountresult= array();
$fetchresult = mysqli_query($conn, "SELECT AVG(results.percentage), exam_paper.examTitle FROM results INNER JOIN exam_paper ON results.examPaperID = exam_paper.examPaperID GROUP by results.examPaperID ORDER by results.examPaperID");
while($rowresult= mysqli_fetch_assoc($fetchresult)){
    $examPapertitle[] = $rowresult['examTitle'];
    $avgcountresult[] = $rowresult['AVG(results.percentage)'];
}


<canvas id="myChart" style="width:100%;max-width:600px"></canvas>

Advertisement

Answer

I believe that your issue is that your var xValues = needs an input of let’s say [44,100,50.29,100] and instead you are echoing 4410050.29100

So you need to echo those values correctly, you can either change your php block like so:

var xValues =[<?php foreach($examPapertitle as $k=>$title) {
                        echo $title.($k>0?",":"");
                        }; ?>]

Or to use much easier to read functions:

var xValues =[<?php echo implode($examPapertitle,",") ?>]

This is if your values are numbers, you will need to wrap those values in quotes for strings, like so:

var xValues =["<?php echo implode($examPapertitle,'","') ?>"]

If you need more info about how implode works, you can check it’s manual here

PS: a handy tip when mixing php and javascript is to always check your php’s output (aka the browser source file) through the web inspector. It makes it much easier to catch issues like this.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement