2016-04-22 264 views
0

因此,我目前有圖表具有來自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> 

DB結構 http://prntscr.com/avdg9r

頁面 http://prntscr.com/avdgeq

回答

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++; 

} 

此外,循環你的$天數組。

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++; 
} 
?> 
] 
+0

唉唉,是的,只是編輯的感謝。仍然顯示空白 –

+0

非常感謝!我已經把它展示出來了,有什麼想法我可以如何在1天內一起添加所有時間? –

+0

我在循環中添加了一個變量'$ total'。使用'echo $ total'來顯示循環外**的總數**。 – fislerdata

0

移動你的I $循環塊外,否則$ I爲0每次迭代

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

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

}