sayousaad sayousaad - 5 months ago 25
Javascript Question

Error In Javascript code with php

I wanna make statistics in my website for the last 3 years

I want to show result like this

2016 : 159
2015 : 132
2014 : 200


I try my code (this's)

$date2 = date('Y');
$n = $date2;
for($i=$n-2;$i<=$n;$i++) {
$sql = "SELECT sum(count) AS value_sum FROM statistics where YEAR(st_date) = $i ";
$sql_sel = mysqli_query($conn,$sql);
echo '
<script>
var pieData = [
';

while($rows = mysqli_fetch_assoc($sql_sel)) {
if($i == $n-2) {
echo '{
value: '.$rows['value_sum'].',
color:"#337AB7"
},';
}
else if($i == $n-1) {
echo '{
value: '.$rows['value_sum'].',
color:"#FC8213"
},';
}
else if($i == $n) {
echo '{
value: '.$rows['value_sum'].',
color:"#8BC34A"
},';
}
echo'];
new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData);
</script>';
}}
?>


but this code give me just 1 one row like this

2016 : 159

I wanna see all result, any help ?

Answer

This should help you out:

<?php
// Store the array for the pie data within PHP at first
$js_pie_data = [];

// Define colors
$colors = [
    date('Y') => '8BC34A',  // current year
    (date('Y') - 1) => 'FC8213', // last year
    (date('Y') - 2) => '337AB7' // 2 years ago
];

$sql = "SELECT
            YEAR(st_date) as `year`,
            sum(count) AS value_sum
        FROM
            statistics
        WHERE
            YEAR(st_date) >= (YEAR(CURDATE())-2)
        GROUP BY
            YEAR(st_date)";

$sql_sel = mysqli_query($conn,$sql);

while($rows = mysqli_fetch_assoc($sql_sel))
{
    $js_pie_data[] = [
        'value' => $rows['value_sum'],
        'color' => '#'.$colors[$rows['year']]
    ];
}

echo '<script>
var pieData = '.json_encode($js_pie_data).';
new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData);
</script>';