Google Pie Chart Using PHP

Google Pie Chart With PHP

The Google pie chart below is made from querying the mySQL database. Then, an array is made. The array must fit exactly the same way as it is presented in the javascript file. After the array is built, you add PHP code into the Javascript.

Add the code:
<?php echo implode(“,”, $myurl); ?>

This code turns the array into a string that replaces hard coded values.


//get columnname id
$command = “SELECT DISTINCT lastname FROM table_sort “;
$result = mysqli_query($db, $command);
while ($row = mysqli_fetch_assoc($result)) {
$lastname = trim(addslashes($row[‘lastname’]));
$lastnamearray[] = $lastname;

//get the count
$commandb = “SELECT count(*) as cnt FROM table_sort WHERE lastname =’$lastname’ “;
$resultb = mysqli_query($db, $commandb);
while($row = mysqli_fetch_assoc($resultb)) {
$cnt = $row[‘cnt’];
$myurl[] = “[‘”.$lastname.”’,”.$cnt.”]”;


<!--Load the AJAX API-->
<script type=”text/javascript” src=””></script>
<script type=”text/javascript”>

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

// Set a callback to run when the Google Visualization API is loaded.

// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {

// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn(‘string’, ‘Rep’);
data.addColumn(‘number’, ‘Assigned Leads’);
/* [‘Mushrooms’, 3],
[‘Onions’, 1],
[‘Olives’, 1],
[‘Zucchini’, 1],
[‘Pepperoni’, 2]*/

<?php echo implode(“,”, $myurl); ?>

// Set chart options
var options = {‘title’:’Display Last Names’,

// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById(‘chart_div’));
chart.draw(data, options);

<!--Div that will hold the pie chart-->
<div id=”chart_div”></div>