I have tried to display a data from MySQL table in line chart. the x-axis hold the staff names and y-axis contains the id number. I faced a problem that the string (staff name) is not showing in the x-axis and it shows only the numeric value
The code that I have tried so far is:
<?php
$dataPoints = array();
//Best practice is to create a separate file for handling connection to database
try{
// Creating a new connection.
// Replace your-hostname, your-db, your-username, your-password according to your database
$link = new PDO('mysql:host=localhost;dbname=aa', 'root', '');
$handle = $link->prepare('select * from staff');
$handle->execute();
$result = $handle->fetchAll(PDO::FETCH_OBJ);
foreach($result as $row){
array_push($dataPoints, array("x"=> $row->Name, "y"=> $row->id));
}
$link = null;
}
catch(PDOException $ex){
print($ex->getMessage());
}
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "light1",
title:{
text: "PHP Column Chart from Database"
},
xaxis
data: [{
type: "line", //change type to bar, line, area, pie, etc
yValueFormatString: "$#,##0K",
indexLabel: "{y}",
indexLabelPlacement: "inside",
indexLabelFontWeight: "bolder",
indexLabelFontColor: "white",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
</head>
<body>
<center><div id="chartContainer" style="height: 370px; width: 50%;"></div></center>
<script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
</body>
</html>