Home > Article > Backend Development > How can I create Google Charts from MySQL data using PHP and JSON?
In this article, we'll explore a detailed guide on generating Google Charts using MySQL table data as the data source. We'll primarily focus on a non-Ajax example to simplify the understanding.
Before we begin, ensure you have the following prerequisites:
Create a table named "googlechart" with the following columns:
<?php // Connect to the database $con = mysql_connect("localhost", "username", "password"); mysql_select_db("chart", $con); // Query the "googlechart" table $sth = mysql_query("SELECT * FROM googlechart"); // Initialize the data table $table = array(); $table['cols'] = array( // Column labels array('label' => 'Weekly Task', 'type' => 'string'), array('label' => 'Percentage', 'type' => 'number') ); // Populate the table with data from the query result $rows = array(); while ($r = mysql_fetch_assoc($sth)) { $temp = array(); $temp[] = array('v' => $r['weekly_task']); $temp[] = array('v' => $r['percentage']); $rows[] = array('c' => $temp); } $table['rows'] = $rows; // Convert the table data to JSON format $jsonTable = json_encode($table); ?>
<html> <head> <script src="https://www.google.com/jsapi"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script> google.load('visualization', '1', {'packages':['corechart']}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>); var options = { title: 'My Weekly Plan', is3D: true, width: 800, height: 600 }; var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <div>
You may encounter an error while using short tags (=):
syntax error var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
To resolve this, use the following syntax instead:
<?php echo $jsonTable; ?>
Now, you have a comprehensive understanding of how to use PHP, MySQL, and JSON to create Google Charts from your database data.
The above is the detailed content of How can I create Google Charts from MySQL data using PHP and JSON?. For more information, please follow other related articles on the PHP Chinese website!