I'm new to charts in php and Jquery. I have a table in mysql name students with a field 'gender'. I want to take a percentage of each of the two gender (Male and Female) over the total and represent it in a doughnut chart as percentage. I have the following codes but not working.
php
<?php
header('Content-Type: application/json');
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'siloam');
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
$query=sprintf(
"select gender,
gender * 100
/ (SELECT SUM(gender)
FROM students
WHERE gender = 'Male')
AS male_percent
from students AND gender * 100
/ (SELECT SUM(gender)
FROM students
WHERE gender = 'Female')
AS female_percent
from students ");
$result = $mysqli->query($query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
//close connection
$mysqli->close();
print json_encode($data);
Js
$(document).ready(function(){
$.ajax({
url : "data.php",
type : "GET",
success : function(data) {
console.log(data);
var ctx1 = $("#doughnut-chartcanvas-1");
var data1 = {
labels : ["Male", "Female""],
datasets : [
{
label : "gender",
data : data,
backgroundColor : [
"#DEB887",
"#A9A9A9"
],
borderColor : [
"#CDA776",
"#989898"
],
borderWidth : [1,1]
}
]
};
var options1 = {
title : {
display : true,
position : "top",
text : "Percentage of Students Per Gender",
fontSize : 18,
fontColor : "#111"
},
legend : {
display : true,
position : "bottom"
}
};
var chart1 = new Chart( ctx1, {
type : "doughnut",
data : data1,
options : options1
} );
},
error : function(data) {
console.log(data);
}
});
});
html
<div class="chart-container">
<div class="doughnut-chart-container">
<canvas id="doughnut-chartcanvas-1"></canvas>
</div>
</div>
Is there any better way to do this, or may be how to fix the codes, please someone help.