[Chartjs]-How to retrieve data from mysql to chart.js

1๐Ÿ‘

โœ…

1- get the company name and SUM of total_of_gp_fee group by company.

include_once("connection.php");

//get the company name and total_of_gp_fee of that company.
$results_sum = "SELECT cshortcut,SUM(total_of_gp_fee) AS Total FROM gp GROUP BY cshortcut";
$result_sum = mysqli_query($conn, $results_sum) or die("error to fetch data");
if ($result_sum->num_rows > 0) {
    // output data of each row
    $labels = $data = '';
    while($row = $result_sum->fetch_assoc()) {

        //get the company name separated by comma for chart labels
        $labels.= '"' .$row["cshortcut"]. '",';

        //get the total separated by comma for chart data
        $data.= $row["Total"].',';
    }
}

2- Update the value of labels and data in chart.

labels: [<?php echo trim($labels);?>],
            datasets: [{
                    label: '# of Votes',
                    data: [<?php echo trim($data);?>],

3- Add the tooltips for bar chart.

options: {
            scales: {
                yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
            },

            //Add the tooltips
            tooltips: {
                    callbacks: {
                        label: function(tooltipItem) {
                            return "โ‚ฌ" + Number(tooltipItem.yLabel);
                        }
                    }
            },
        }

4- Add tooltips for pie chart.

tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        var allData = data.datasets[tooltipItem.datasetIndex].data;
                        var tooltipData = allData[tooltipItem.index];
                        var total = 0;
                        for (var i in allData) {
                            total += allData[i];
                        }
                        var tooltipPercentage = Math.round((tooltipData / total) * 100);
                        return "โ‚ฌ" + ': ' + tooltipData + ' (' + tooltipPercentage + '%)';
                    }
                }
            },

0๐Ÿ‘

I think cshortcut holds the name of the comany, so you can do it all with one query:

$results_sum = "SELECT cshortcut,SUM(total_of_gp_fee) AS Total FROM gp GROUP BY cshortcut";

And you will get an array with to elements (cshortcut and Total) for each element in the array

Anyway, you have an error in your JS, you are using a name that doesn โ€˜t exist in your data (total_of_gp_fee) because you are using an alias (Total), you should change:

        labels: [<?php while ($b = mysqli_fetch_array($result_cut)) { echo '"' . $b['cshortcut'] . '",';}?>],
        datasets: [{
                label: '# of Votes',
                data: [<?php while ($p = mysqli_fetch_array($sum)) { echo '"' . $p['Total'] . '",';}?>],

Leave a comment