2013-11-25 21 views
2

我正在嘗試創建條形圖。我使用了一些我在github上發現的庫來做到這一點。但是現在我無法將從數據庫中提取的變量(只是一些數字)傳遞到JavaScript上的數據部分。如果任何人都可以提供一些技巧或幫助,那就太棒了。如何將數據庫中的數字傳遞給JavaScript數據部分?

<!DOCTYPE html> 
    <html lang="en"> 
     <head> 
     <script src="Chart.js"></script> 
     <meta charset="utf-8" /> 
     <title>index</title> 
     </head> 
     <body> 
     <h1>Sales for last three months </h1> 
     <?php 
     require("files/connect.php"); 
     $queryJan = "SELECT sales_records FROM games WHERE sale_month='Jan'"; 
     $queryFeb = "SELECT sales_records FROM games WHERE sale_month='Feb'"; 
     $queryMar = "SELECT sales_records FROM games WHERE sale_month='Mar'"; 

     $Jan = mysqli_query($connection,$queryJan) or die(mysqli_error($connection)); 
     $Feb = mysqli_query($connection,$queryFeb) or die(mysqli_error($connection)); 
     $Mar = mysqli_query($connection,$queryMar) or die(mysqli_error($connection)); 

     //Information I want to pass to the javascript. 
     $JanArray = mysqli_fetch_array($Jan); 
     $FebArray = mysqli_fetch_array($Feb); 
     $MarArray = mysqli_fetch_array($Mar); 



     ?> 

    <canvas id="canvas" height="450" width="600"></canvas> 
     <canvas id="canvas" height="450" width="600"></canvas> 
      <script> 
      var barChartData = { 
       labels : ["January","February","March"], 
       datasets : [ 
        { 
         fillColor : "rgba(220,220,220,0.5)", 
         strokeColor : "rgba(220,220,220,1)", 
         data : [] 
         //I want to put the information in here and it will create a bar chart 

        }, 
        { 
         fillColor : "rgba(151,187,205,0.5)", 
         strokeColor : "rgba(151,187,205,1)", 
         data : [] 
        }, 
        { 
         fillColor : "rgba(151,187,205,0.5)", 
         strokeColor : "rgba(151,187,205,1)", 
         data : [] 
        } 
       ] 

      } 

     var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData); 

     </script> 



     </body> 
    </html> 
+2

不要混用'mysqli_ *'和'mysql_ *'功能! –

+1

三個獨立的查詢可以很容易地作爲一個單獨運行? Ouch ... –

+0

我知道我沒有太多時間,我只需要快速做到這一點。 –

回答

4

只是讓PHP回聲出數組作爲JSON ...

data : <?php echo json_encode($JanArray); ?> 

是會做到這一點。

編輯: 你需要獲取數據這樣...

<?php 
    ... 
    $JanArray = array(); 
    while($row = mysqli_fetch_array($Jan)) { 
     $JanArray[] = $row[0]; // this fetches the data of the first column 
    } 
?> 
+0

乾杯我會給它一個去。 –

+1

實際上,您將需要重新格式化數組,因爲它將包含列名稱。看到我的編輯... –

+0

感謝一百萬邁克爾。當我回到家時,會放棄它。 –

相關問題