I am trying to link MySql with echarts to make my data to have a better visualisation. However, there is something wrong when I tried out this.
My SQL table:
there is two php file, one is to connect to mySQL (process.php), the other is to display the charts(testing.php).
The code for process.php is below:
<?php
header("Content-type=text/json;charset=UTF-8");
$connect = mysqli_connect("localhost", "fypdb", "password123", "fyp");
$query = "SELECT * FROM study";
$result = mysqli_query($connect, $query);
$data = array();
class User{
public $username;
public $age;
}
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$user = new User();
$user->username = $row['name'];
$user->age = $row['age'];
$user->salary = $row['salary'];
$data[] = $user;
}
mysqli_close($connect);
echo json_encode($data);
?>
The code for testing.php is below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/echarts.js" type="text/javascript"></script>
<script src="js/jquery-1.12.3.js" type="text/javascript"></script>
</head>
<body>
<div id='container' style="width: 600px; height: 400px;"></div>
<script>
var names = [], ages = [], salaries = [];
function getusers() {
$.ajax({
type: "post",
async: false,
url: "process.php",
data: {},
dataType: "json",
success: function (result) {
if (result) {
for (var i = 0; i < result.length; i++) {
names.push(result[i].username);
ages.push(result[i].age);
salaries.push(result[i].salary);
}
}
},
error: function (errmsg) {
alert("Ajax data is wrong!" + errmsg);
}
});
return names, ages;
}
// getting data from process.php
getusers();
var myChart = echarts.init(document.getElementById("container"));
var option = {
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b}: {c} ({d}%)"
},
legend: {
orient: 'vertical',
x: 'left',
data: names
},
series: [
{
name: 'name',
type: 'pie',
radius: ['50%', '70%'],
avoidLabelOverlap: false,
label: {
normal: {
show: false,
position: 'center'
},
emphasis: {
show: true,
textStyle: {
fontSize: '30',
fontWeight: 'bold'
}
}
},
labelLine: {
normal: {
show: false
}
},
data: [
{value: ages,name:names}
]
}
]
};
myChart.setOption(option);
</script>
</body>
</html>
The JS link is below (Full):
https://ecomfe.github.io/echarts-doc/public/en/download.html
The output here is below which it should be in different color: