我需要一些幫助。我想用Google的圖表api和通過MySql獲取的數據創建一個動態折線圖。我使用PHP來創建頁面。我能夠創建一個硬編碼值的簡單圖表沒有問題。現在我試圖使用一些MySql數據,但沒有運氣。我的網頁看起來是這樣的:使用谷歌圖表,mysql和php創建動態圖表
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var jsonData = $.ajax({
url: "graphData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {'title':'Ticket Sales',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
<?
PrintHeader($buf,$username,$userid,$session);
echo("<div id='chart_div'></div>");
?>
</html>
然後我graphData.php網頁看起來是這樣的:
$sql = "SELECT MONTHNAME(DATE_SOLD), COUNT(*) FROM TICKET_SALES WHERE YEAR(DATE_SOLD) = 2012 GROUP BY MONTHNAME(DATE_SOLD) ORDER BY MONTH(DATE_SOLD);";
$result = mysql_query($sql, $conn) or die(mysql_error());
//start the json data in the format Google Chart js/API expects to recieve it
$JSONdata = "{
\"cols\": [
{\"label\":\"Month\",\"type\":\"string\"},
{\"label\":\"Ticket Sales\",\"type\":\"number\"}
],
\"rows\": [";
//loop through the db query result set and put into the chart cell values
while($row = mysql_fetch_row($result))
{
$JSONdata .= "{\"c\":[{\"v\": " . $row[0] . "}, {\"v\": " . $row[1] ."}]},";
}
//end the json data/object literal with the correct syntax
$JSONdata .= "]}";
echo $JSONdata;
?>
當我加載在瀏覽器中我只是得到一個紅色的盒子,上面寫着在網頁「表有沒有列。」誰能告訴我我做錯了什麼?或者也許更好/更簡單的方法?任何幫助將不勝感激!!
請勿以這種方式構建JSON數據,創建一個PHP數組並使用'json_encode()'發回數據。 – Orbling