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

时间:2018-10-15 07:05:04

标签: php mysql linechart canvasjs

我试图在折线图中显示来自MySQL表的数据。 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>  

2 个答案:

答案 0 :(得分:2)

x-value可以是数字或dateTime值。但就您而言,这似乎是一个字符串。您可以使用axis label,而不要使用x值。

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

答案 1 :(得分:1)

如果您看到有关CanvasJS数据点属性x的文档,则仅接受数字值,而应使用label。 尝试更改

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

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