Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

Pie chart using mysql and php

I am using this code from internet. But in this the data is static but i want to draw a chart with my database entries. can u tell me how to add mysql data in this code

<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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a rough code to do this in php, you can change it according to your need:

<?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>

Hope that helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...