使用数据库数据填充图表

时间:2016-04-22 09:50:03

标签: php jquery database

所以我目前有来自JQ的静态数据的图表,我正在尝试使用PHP从数据库获取数据。我已经开始了逻辑,但仍在努力前进,任何想法都会受到赞赏。到目前为止,图形输出空白,仅在我使用静态数据时才有效。

在输出数组中使用0作为测试

PHP<?php

$userID = $_SESSION["userid"];

$days = array();

$query = "SELECT timeSpent
FROM gymTime
WHERE userid = '$userID'";

$result = mysqli_query($conn, $query);
$i=0;
while($row = $result->fetch_assoc()) {


        $days[$i] = $row["timeSpent"];
        $i++;

     }
?

JQ <script>

// in php you simply need to create the two arrays and teh functionality will work  

// monthly set to minutes
var myTimeMon = ;
var myMonths = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

// weekly data in mins
var myTimeWeek = [<?php echo $days[0]; ?>];
var myDays= ["Mon","Tue","Wed","Thur","Fri","Sat","Sun"];

// default values to be displayed when the page loads
var myLabels =  myDays;
var mydata =  myTimeWeek;

// store value of radiobutton
var currentValue = "m"

var displayData=[];


function contoMins(){
    // change the values of the array
    for(i=0; i<mydata.length; i++){
        mydata[i]=mydata[i]*60;
    }
    destroyChart();
}

// destroy the chart so that it does not load on top of itself
function destroyChart(){
   window.myBar.destroy();
   buildChart();
}

 function buildChart(){
        displayData = mydata;
        var barChartData = {
        labels : myLabels,
        //barValueSpacing : 25,
        //barStrokeWidth : 40,
        datasets : [
            {
                fillColor : "rgba(220,220,220,0.5)",
                strokeColor : "rgba(220,220,220,0.8)",
                highlightFill: "rgba(220,220,220,0.75)",
                highlightStroke: "rgba(220,220,220,1)",
                  data: displayData
            }
        ]

    }

        var ctx = document.getElementById("canvas").getContext("2d");
        window.myBar = new Chart(ctx).Bar(barChartData, {
              barValueSpacing : 10,
        });
    }

 buildChart();
 //sendData();  

    </script>

数据库结构 http://prntscr.com/avdg9r

页面 http://prntscr.com/avdgeq

2 个答案:

答案 0 :(得分:1)

这总是将$ i设为0。

while($row = $result->fetch_assoc()) {

    $i=0;
    $days[$i] = $row["timeSpent"];
    $i++;

 }

在while循环之外移动$ i = 0.

$i=0;
while($row = $result->fetch_assoc()) {

    $days[$i] = $row["timeSpent"];
    $i++;

 }

此外,循环播放$ days数组。

var myTimeWeek = [<?php echo $days[0]; ?>];

只会显示$ days中的第一个元素。你需要遍历数组。

var myTimeWeek = [
<?php
$i = 0;
$total = 0;
foreach ($days as $day)
{
  if ($i > 0) echo ', ';
  echo '"' . $day . '"';
  $total = $total + $day;
  $i++;
}
?>
]

答案 1 :(得分:0)

将$ i移出循环块,否则每次迭代$ i将为0

$i=0;
while($row = $result->fetch_assoc()) {

    $days[$i] = $row["timeSpent"];
    $i++;

 }