在折线图中显示来自 MySQL 数据库的数据

Display data from MySQL database in line chart

我试图在折线图中显示来自 MySQL table 的数据。 x 轴包含员工姓名,y 轴包含 ID 号。我遇到了一个问题,即字符串(员工姓名)没有显示在 x 轴上,它只显示数值 到目前为止我尝试过的代码是:

<?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>  

如果您看到有关 CanvasJS 数据点属性的文档 x only accept number value u should using label。 尝试改变

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

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

x-value can be numeric or a dateTime value. But in your case, it seems to be a string. You can use axis label,而不是你的 x 值。

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