2013-02-20 102 views
0

如何使用我自己的服务器端数据填充Google Chart API,即使用PHPMySQL。Google Chart API数据

目前,我有以下数据:

function drawChart() 
{ 
// Create the data table. 
var data = new google.visualization.DataTable(); 
data.addColumn('string', 'City'); 
data.addColumn('number', 'Number of Crimes'); 
data.addRows([ 
      ['Cardiff', 300], 
      ['London', 900], 
      ['Manchester', 500], 
      ['Dublin', 400], 
      ['Liverpool', 600] 
      ]); 

// Set Chart Options 
var options = { 
    'legend': 'left', 
    'title': 'Crimes (per day)', 
    'is3D': 'True', 
    'width':400, 
    'height':300 
}; 

// Instantiate and Draw Chart. 
var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 
chart.draw(data, options); 
} 

但是我怎么给它的数据从一个表在我的MySQL数据库?

回答

3

你必须让你的数据从数据库的图表API的JavaScript的代码:之前

//Your database query goes here 
$list = mysql_query("SELECT city,crimes FROM TABLE"); 
while($row = mysql_fetch_assoc($list)){ 
    $data[] = "['".$row['city']."', ".$row['crimes']."]"; 
} 
$data_for_chart = implode(",\n"$data); 

现在,在您的JS代码替换:

data.addRows([ 
     ['Cardiff', 300], 
     ['London', 900], 
     ['Manchester', 500], 
     ['Dublin', 400], 
     ['Liverpool', 600] 
     ]); 

有了:

data.addRows([ 
     <?php echo $data_for_chart; ?> 
     ]); 
+0

对不起,你能告诉我在哪里吗?我真的不太擅长这一点。 – 2013-02-20 14:59:33

+0

@JohnSmith:我已经扩展了我的答案。 – oktopus 2013-02-20 15:07:57

+0

问题解决了,非常感谢! – 2013-02-20 15:27:42