I want to draw a line graph using the following data in MySQL table.
date – dec 10 , dec 11, dec 12, dec 13, dec 14, dec 15, dec 16, dec17, dec,18,dec 19, dec 20
attendance – 65, 58, 56, 78, 51, 54, 69, 35, 68, 43, 52
I made two queries extracting the data and stored in 2 arrays namely $data1
and $data2
using the code below
$con = new mysqli($servername, $username, $password, $db);
$myquery1 = "select date from Table_attendance";
$query1 = mysqli_query($con, $myquery1);
if ( ! $query1 ) {
echo mysqli_error();
die;
}
for ($x = 0; $x < mysqli_num_rows($query1); $x++) {
$data1[] = mysqli_fetch_assoc($query1);
}
$my1 = "select attendance from Table_attendance";
$qu1 = mysqli_query($con, $my1);
if ( ! $qu1 ) {
echo mysqli_error();
die;
}
for ($x = 0; $x < mysqli_num_rows($qu1); $x++) {
$data2[] = mysqli_fetch_assoc($qu1);
}
I then encoded the two arrays $data1
and $data2
into json format using the following code.
$encod = json_encode($data1);
$encod2 = json_encode($data2);
The output of the arrays were as follows.
[{“date”:”2021-12- 10″},{“date”:”2021-12-11″},{“date”:”2021-12-12″},{“date”:”2021-12-13″},{“date”:”2021-12-14″},{“date”:”2021-12-15″},{“date”:”2021-12-16″},{“date”:”2021-12-17″},{“date”:”2021-12-18″},{“date”:”2021-12-19″},{“date”:”2021-12-20″}]
[{“attendance “:”65”},{“attendance “:” 58 “},{“attendance “:” 56″},{“attendance”:” 78 “},{“attendance “:” 51 “},{“attendance “:” 54″}{“attendance “:”69 “},{“attendance “:”35”},{“attendance”:”68″},{“attendance”:”43″},{“attendance “:”52”}]
Finally I tried passing the encoded values as follows to plot into a line graph but it didn’t work.
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<canvas id="myChart" style="width:100%;max-width:600px"></canvas>
<script>
var xValues = <?php echo $encod?>;
var yValues = <?php echo $encod2?>;
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues
}]
},
options: {
title: {display: true, text: 'Custom Chart Title'},
legend: {display: false},
scales: {
yAxes: [{ticks: {min: 6, max:16}}],
}
}
});
</script>
Please help me with this assessment. If there is another better code than mine please be kind enough to share.