0

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>  

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.