簡體   English   中英

如何使用mysql數據庫中的數據創建Google ComboChart?

[英]How to create Google ComboChart with data from mysql database?

我在PHP腳本中從mysql數據庫中提取數據,並使用谷歌圖表以圖形方式顯示數據。 當使用只有2個變量來處理的餅圖或條形圖時,它工作正常。 現在我想使用ComboChart。 我在表中有4個字段:名稱,日期,數量,成本。 我想要一個ComboChart,其中x軸是Date,條形圖表示Quantity,線圖表示Cost。

這是我到目前為止的代碼。 我該怎么做呢? 在drawChart()函數中,x軸或y軸沒有明確的順序,所以我怎么知道我的哪些數據顯示在哪里? 這取決於您在mysqli_query期間選擇數據的順序嗎?

// host, username, password and dbname are already declared

$conn = mysqli_connect($host, $username, $password);
if ($conn->connect_error) {
        die("Could not connect: " . mysql_error()) . "<br>";
}
mysqli_select_db($conn, $dbname);

$qresult = mysqli_query($conn, "SELECT * FROM Scrap");

$rows = array();
$table = array();
$table['cols'] = array(
        array('label' => 'Date', 'type' => 'string'),
        array('label' => 'Quantity', 'type' => 'number'),
        array('label' => 'Cost', 'type' => 'number')
);

$rows = array();
while ($r = $qresult->fetch_assoc()) {
        $temp = array();
        $temp[] = array('v' => (string) $r['Date']);
    // Values of each slice
    $temp[] = array('v' => (int) $r['Quantity']);
    $temp[] = array('v' => (float) $r['Cost']);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>

<html>
  <head>
    <!--Load the Ajax API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(<?=$jsonTable?>);
      var options = {
        title: 'YTD Controllable Scrap Costs',
        seriesType:'bars',
        series:{2: {type: 'line'}}
//        width: 800,
//        height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

所以我測試了周圍,我發現第一列是x軸,第二列,第三,第四列等在y軸上。 條形圖和線圖沒有顯示的原因是因為在我的drawChart()函數中,它表示: series:{2: {type: 'line'}} ,數字2指的是y的第3個字段-axis因為它是零索引的。 我沒有y軸的第3個字段,所以我將其切換為series:{1: {type: 'line'}}現在我得到一個條形圖和折線圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM