我设法使PHP和JavaScript代码在同一页面上工作。在左侧页面的顶部,您可以看到我的php表中的数据已正确提取,但是,当我将php代码粘贴到需要保留表“数据”的位置时,它没有。即使被php标签包围也无法正常工作。
<?php
$conn = mysqli_connect("localhost", "x", "y", "z");
$query = "SELECT * FROM `checkPointMod`";
$result = $conn -> query($query);
while($row = $result -> fetch_assoc())
{
echo $row['mod1']."<br>";
echo $row['mod2']."<br>";
echo $row['mod3']."<br>";
echo $row['mod4']."<br>";
echo $row['mod5']."<br>";
echo $row['mod6']."<br>";
}
$conn -> close();
?>
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
</head>
<body style="background-color: lightgrey;">
<div class="col-md-4 text-center">Third of Page - Middle section with progress bar
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<script type="text/javascript">
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [<?php echo $row['mod1']?>, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
</html>
更新:-我去检查element来查看输出是什么,在这里看到了,我还放置了mod2来查看是否会出现6 ...
答案 0 :(得分:2)
我错过了$row
仅存在于while循环内的情况。
用以下内容替换while循环:
$rows = [];
while ($row = $result -> fetch_assoc()) $rows[] = $row;
在您的Javascript代码中,在顶部添加以下代码:
const data = <?= json_encode($rows, JSON_NUMERIC_CHECK) ?>;
您应该在页面源代码中结束此操作
const data = [{ "checkPID": 6, "mod1": 0, "mod2": 6, "mod3": 0, "mod4": 3, "mod5": 2, "mod6": 1, "idUsers": 1 }];
现在您可以在图表设置中执行以下操作:
data: Object.keys(data[0]).filter(key => key.startsWith("mod")).map(key => data[0][key]),