Zahraa Ali
Zahraa Ali

Reputation: 75

Display data from MySQL database in line chart

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();

 try{

$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://canvasjs.com/assets/script/canvasjs.min.js"> 
      </script>
       </body>
       </html>  

Upvotes: 0

Views: 1397

Answers (2)

anggito wibisono
anggito wibisono

Reputation: 89

If u see documentation about CanvasJS datapoint attribute x only accept number value u should using label. try to change

array_push($dataPoints, array("x"=> $row->Name, "y"=> $row->id));

to

array_push($dataPoints, array("label"=> $row->Name, "y"=> $row->id));

Upvotes: 1

Vishwas R
Vishwas R

Reputation: 3420

x-value can be numeric or a dateTime value. But in your case, it seems to be a string. You can use axis label, instead of x-value in your case.

array_push($dataPoints, array("label"=> $row->Name, "y"=> $row->id));

Upvotes: 2

Related Questions