使用mysql和php的饼图

时间:2015-08-24 07:07:30

标签: php mysql charts google-visualization

我正在使用来自互联网的此代码。但在这个数据是静态的,但我想绘制一个包含我的数据库条目的图表。你可以告诉我如何在这段代码中添加mysql数据

<div class="hellcontainer">

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<dcript type="text/javascript">
google.load("visualization","1",{packages:["corechar"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
	var data=google.visualization.arrayToDataTable([
	['Languages','speakers(in millions)'],
	['Assamese,13'],['Punjabi',45]]);
	var options = {
		title:''
	};
	var chart=new google.visualization.PieChart(document.getElementById('chart_div'));
	chart.draw(data,options);
	
}
</script>

2 个答案:

答案 0 :(得分:2)

这是在php中执行此操作的粗略代码,您可以根据需要进行更改:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$db = "dbname";

$conn = mysqli_connect($servername, $username, $password, $db); // update your connection params

$query = "SELECT state, lang_number FROM state"; //update your query as needed

$results = mysqli_query($conn, $query);
$pieData = array();

while ($row = mysqli_fetch_array($results)) {
    $acc_type = $row ['state'];
    $acc_num = $row ['lang_number'];
    $pieData[] = array($row['state'], $row['lang_number']);
}
?>

<div class="hellcontainer">
    <div id="chart_div"></div>
</div>

<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">
google.load("visualization","1",{packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'State');
    data.addColumn('number', 'speakers(in millions)');
    data.addRows(<?php echo json_encode($pieData, JSON_NUMERIC_CHECK); ?>);

    var options = {'title':'Language spoken',
                           'width':400,
                           'height':300};

    var chart=new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data,options);

}
</script>

希望有所帮助。

答案 1 :(得分:0)

<div class="hellcontainer">

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<dcript type="text/javascript">
google.load("visualization","1",{packages:["corechar"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
	var data=google.visualization.arrayToDataTable([
	['Languages','speakers(in millions)'],
	['Assamese,13'],['Punjabi',45]]);
	var options = {
		title:''
	};
	var chart=new google.visualization.PieChart(document.getElementById('chart_div'));
	chart.draw(data,options);
	
}
</script>