我正在尝试创建条形图。我使用了在 github 上找到的一些库来执行此操作。但现在我无法将从数据库中提取的变量(只是一些数字)传递到 JavaScript 的数据部分。如果有人可以提供一些提示或帮助,那就太好了。
<!DOCTYPE html>
<html lang="en">
<head>
<script src="Chart.js"></script>
<meta charset="utf-8" />
<title>index</title>
</head>
<body>
<h1>Sales for last three months </h1>
<?php
require("files/connect.php");
$queryJan = "SELECT sales_records FROM games WHERE sale_month='Jan'";
$queryFeb = "SELECT sales_records FROM games WHERE sale_month='Feb'";
$queryMar = "SELECT sales_records FROM games WHERE sale_month='Mar'";
$Jan = mysqli_query($connection,$queryJan) or die(mysqli_error($connection));
$Feb = mysqli_query($connection,$queryFeb) or die(mysqli_error($connection));
$Mar = mysqli_query($connection,$queryMar) or die(mysqli_error($connection));
//Information I want to pass to the javascript.
$JanArray = mysqli_fetch_array($Jan);
$FebArray = mysqli_fetch_array($Feb);
$MarArray = mysqli_fetch_array($Mar);
?>
<canvas id="canvas" height="450" width="600"></canvas>
<canvas id="canvas" height="450" width="600"></canvas>
<script>
var barChartData = {
labels : ["January","February","March"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : []
//I want to put the information in here and it will create a bar chart
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
data : []
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
data : []
}
]
}
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData);
</script>
</body>
</html>
最佳答案
只需让 php 将数组回显为 json...
data : <?php echo json_encode($JanArray); ?>
这样就可以了。
编辑: 您将需要获取这样的数据...
<?php
...
$JanArray = array();
while($row = mysqli_fetch_array($Jan)) {
$JanArray[] = $row[0]; // this fetches the data of the first column
}
?>
关于javascript - 如何将从数据库中提取的数字传递到 javascript 数据部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20196107/