首页 > 解决方案 > 我需要一个 PHP 查询来从数据库中获取数据并在我的条形图中使用以获取结果

问题描述

我正在做一个小项目,需要一些关于 PHP 查询的帮助。我本质上是在编写一个小型的 eLearning 类型的模块,所以当用户通过模块时,我会在检查点中写入。但是现在,我在 PHP myAdmin 中的表中手动放置值,我需要的是保存到 checkPointMod(检查点模块)表中的值,以传递到用户仪表板上的条形图/饼图。我只需要一个非常简单的查询,任何帮助都会很棒!

我的桌子截图:

我尝试尝试一些东西(我可能在这里完全偏离轨道......):

    $query = "SELECT * FROM `checkPointMod`";

echo $query;


//3.Execute -----------
$result = $conn -> query($query);



while($row = $result -> fetch_assoc())  // <- While there are still results, fetch those using the assoc array, which creates an array of results from the database using the fields as headings. The arrow is related to OO, it's similar to pass the query on the left to the parameter to the right
  {
    data: [<?php echo $row['mod1']; ?>, <?php echo $row['mod2']; ?>, <?php echo $row['mod3']; ?>, <?php echo $row['mod4']; ?>, <?php echo $row['mod5']; ?>],   //When you add the "" around a html tag, you don't need to open <html> & close.
  }



//4.Disconnect ---------
$conn -> close();

我的饼图代码有效(手动放入数据值):

var ctx = document.getElementById("myChart");

var myDoughnutChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ["Time Management", "Career Coach", "Stress & Wellbeing", "Note Taking", "Exam Prep", "Presentations"],
        datasets: [{
            label: 'Module Tracker',
            data: [6, 4, 2, 0, 3, 1],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

标签: phphtmlbootstrap-4chart.js

解决方案


一般来说,你所拥有的是正确的,我倾向于将我的查询与图表分开编写以保持分离;例如:

<?php
$query="SELECT * FROM checkPointMod";
# echo $query;
$newArray = array();
$result = $conn->query($query);
while($row = $result -> fetch_assoc());  {
    $newArray[] = $row['mod1'];
    $newArray[] = $row['mod2'];
    $newArray[] = $row['mod3'];
    $newArray[] = $row['mod4'];
    $newArray[] = $row['mod5'];
}
$conn -> close();
?>

如果需要,您可以执行 print_r 来检查数组的内容...

然后在您的图表部分:

 data: [<?= $newArray ?>],

希望对您有所帮助...


推荐阅读