我希望能够从php(phpMyAdmin)的sql数据库中获取数据并使用chart.js在条形图中显示。
这里需要详细说明。
目标: 要在条形图中以标签形式显示许可证类型,并以数据显示L1,L2和B4的字数:
50 |
40 | ||
30 | || ||
20 | || || ||
10 | || || ||
-----------------
L1 L2 B4
此刻是我的license_table
(行数多于:-))
------------------------------
|id | display_name | license |
------------------------------
|1 | name1 | L1 |
|2 | name2 | L2 |
|3 | name3 | B4 |
|4 | name4 | L1 |
------------------------------
这是我到目前为止拥有的dblicense.php
代码:
<?php
$dbhost = 'localhost';
$dbname = 'email_licenses';
$dbuser = 'administrator';
$dbpass = '-----';
try{
$dbcon = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $ex){
die($ex->getMessage());
}
$stmt=$dbcon->prepare("SELECT license, COUNT(license)
FROM license_table
WHERE license='L1' OR license='L2' OR license='B4'
GROUP BY license;");
$stmt->execute();
$json=[];
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$json[]= $license;
}
?>
然后是我的license.php
:
<?php include'dblicenses.php'; ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Reports</title>
</head>
<body>
<div class="col-lg-8 col-md-8 col-sm-8" align="center">
<h3 class="text-center">TICKET REPORT</h3>
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script type="text/javascript">
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: <?php echo json_encode($json);?>,
datasets: [{
label: 'Assigned Licenses',
backgroundColor: 'rgba(36,247,27,1.00)',
borderColor: 'rgb(36,247,27,1.00)',
data: <?php echo json_encode($json);?>,
}]
},
// Configuration options go here
options: {}
});
</script>
</div>
</body>
</html>
通过测试此代码,我得到以下信息:(不显示任何数据)
1 |
2 |
0 |
-2 |
-1 |
-----------------
L1 L2 B4
总结:我需要获得L1,L2和B4的总字数,并在条形图中显示数据,而L1,L2和B4也要显示为标签。
真的希望有人可以帮助我吗?
谢谢
答案 0 :(得分:0)
您不会把计数放在任何地方。标签需要一个数组,计数需要另一个数组。
$stmt=$dbcon->prepare("SELECT license, COUNT(license) AS count
FROM license_table
WHERE license IN ('L1', 'L2', 'B4')
GROUP BY license;");
$stmt->execute();
$labels=[];
$counts = [];
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$labels[]= $row['license'];
$counts[] = $row['count'];
}
然后,您可以在labels:
选项中使用一个,而在data:
中使用另一个。
data: {
labels: <?php echo json_encode($labels);?>,
datasets: [{
label: 'Assigned Licenses',
backgroundColor: 'rgba(36,247,27,1.00)',
borderColor: 'rgb(36,247,27,1.00)',
data: <?php echo json_encode($counts);?>,
}]
},