使用Chartjs和PHP创建图表

时间:2017-03-14 09:38:30

标签: php chart.js

我需要使用chartJS创建一个图表,它从mysql获取数据,下面是mysql表的示例输出:

+----+------------+----------+-----------------+----------
| ID | DATE       | Time     | Create | Delete | Product |
+----+------------+----------+-----------------+---------+
|  1 | 03/12/2017 | 09:00:00 |     28 |   1264 |      59 | 

我设法将数据放在JSON格式中,使用全局here,下面是PHP文件:

get.php

<?php

$DB_NAME = 'testDB';
$DB_HOST = 'localhost';
$db_port = '3306';
$DB_USER = 'test';
$DB_PASS = 'mysql';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  }

  $result = $mysqli->query('Select * from (SELECT * FROM Stats ORDER BY id DESC LIMIT 48)t ORDER BY id ASC');
  $rows = array();
  $table = array();
  $table['cols'] = array(
    array('label' => 'Time', 'type' => 'string'),
   array('label' => 'ProductCreate', 'type' => 'number'),
   array('label' => 'ProductDelete', 'type' => 'number'),
   array('label' => 'ProductRenew', 'type' => 'number')

);
    foreach($result as $r) {

      $temp = array();

      $temp[] = array('v' => (string) $r['Time']); 
      $temp[] = array('v' => (int) $r['Create']);
      $temp[] = array('v' => (int) $r['Delete']);
      $temp[] = array('v' => (int) $r['Renew']);

      $rows[] = array('c' => $temp);
    }

$table['rows'] = $rows;

// convert data into JSON format
$SubsStats = json_encode($table);
echo $SubsStats;


?>

我现在的问题是如何将PHP输出包含到我的HTML文件中并使用ChartJS绘制图表?

谢谢, 阿里

3 个答案:

答案 0 :(得分:1)

检查Example

var data = {
	labels : ["January","February","March",
              "April","May","June",
              "July","Agost","September",
              "October","November","December"],
	datasets : [
		{
			fillColor : "rgba(252,233,79,0.5)",
			strokeColor : "rgba(82,75,25,1)",
			pointColor : "rgba(166,152,51,1)",
			pointStrokeColor : "#fff",
			data : <?php echo $res; ?>
		}
	]
}


var options={					
	//Boolean - If we show the scale above the chart data			
	scaleOverlay : false,
	
	//Boolean - If we want to override with a hard coded scale
	scaleOverride : true,
	
	//** Required if scaleOverride is true **
	//Number - The number of steps in a hard coded scale
	scaleSteps : 14,
	//Number - The value jump in the hard coded scale
	scaleStepWidth : 5,
	//Number - The scale starting value
	scaleStartValue : 55,
	//String - Colour of the scale line	
	scaleLineColor : "rgba(20,20,20,.7)",
	
	//Number - Pixel width of the scale line	
	scaleLineWidth : 1,

	//Boolean - Whether to show labels on the scale	
	scaleShowLabels : true,
	
	//Interpolated JS string - can access value
	scaleLabel : "<%=value%>",
	
	//String - Scale label font declaration for the scale label
	scaleFontFamily : "'Arial'",
	
	//Number - Scale label font size in pixels	
	scaleFontSize : 12,
	
	//String - Scale label font weight style	
	scaleFontStyle : "normal",
	
	//String - Scale label font colour	
	scaleFontColor : "#666",	
	
	///Boolean - Whether grid lines are shown across the chart
	scaleShowGridLines : true,
	
	//String - Colour of the grid lines
	scaleGridLineColor : "rgba(0,0,0,.3)",
	
	//Number - Width of the grid lines
	scaleGridLineWidth : 1,	
	
	//Boolean - Whether the line is curved between points
	bezierCurve : true,
	
	//Boolean - Whether to show a dot for each point
	pointDot : true,
	
	//Number - Radius of each point dot in pixels
	pointDotRadius : 5,
	
	//Number - Pixel width of point dot stroke
	pointDotStrokeWidth : 1,
	
	//Boolean - Whether to show a stroke for datasets
	datasetStroke : true,
	
	//Number - Pixel width of dataset stroke
	datasetStrokeWidth : 2,
	
	//Boolean - Whether to fill the dataset with a colour
	datasetFill : true,
	
	//Boolean - Whether to animate the chart
	animation : false,

	//Number - Number of animation steps
	animationSteps : 60,
	
	//String - Animation easing effect
	animationEasing : "easeOutQuart",

	//Function - Fires when the animation is complete
	onAnimationComplete : null
};


//Get context with jQuery - using jQuery's .get() method.
var ctx = $("#myChart").get(0).getContext("2d");


new Chart(ctx).Line(data,options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://www.chartjs.org/assets/Chart.js"></script>
<canvas id="myChart" width="500" height="300"></canvas>

  

PHP代码: - (以上js代码)

<?php 

$array = array(65,68,75,81,95,105,130,120,105,90,75,70);

$res = json_encode($array);
?>

答案 1 :(得分:0)

您可以创建AJAX并返回图表的json。 jquery示例。

$.ajax({
  url: "get.php",
   dataType: 'json',
   method: "POST",
  dataType:"json",
  data: data,
  success: function (responce) {
     //create this charts
  }
})

您可以在get.php中创建js变量或查看。

<script>
    var data = <?php echo $SubsStats; ?>;
    var responce = JSON.parse(data);
    new Chart(ctx).Line(data,options);
</script>

ChartsJs documentation

答案 2 :(得分:0)

$data = array(
    array("label"=> row['id'], "y"=> row['value']),
    array("label"=> row['column1'], "y"=> row['value1']),
    array("label"=> row['column2'], "y"=> row['value2']),
        );

?>