PHP MySQL Google Chart JSON - Complete Example
This example shows you how to generate a chart using PHP, MySQL and the Google Chart API.
Prerequisites:
Database Setup:
PHP-MySQL-JSON-Google Chart Example:
$con = mysqli_connect("localhost", "Username", "Password") or die("Failed to connect with database!!!!"); mysqli_select_db("Database Name", $con); $result = mysqli_query($con, "SELECT * FROM googlechart"); $rows = array(); $table = array(); $table['cols'] = array( array('label' => 'Weekly Task', 'type' => 'string'), array('label' => 'Percentage', 'type' => 'number') ); while ($row = mysqli_fetch_assoc($result)) { $temp = array(); $temp[] = array('v' => (string) $row['weekly_task']); $temp[] = array('v' => (int) $row['percentage']); $rows[] = array('c' => $temp); } $table['rows'] = $rows; $jsonTable = json_encode($table); echo $jsonTable; ?> <html> <head> <!-- Load the Ajax API --> <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"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages': ['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); function drawChart() { // Create our data table out of JSON data loaded from server. var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>); var options = { title: 'My Weekly Plan', is3D: 'true', width: 800, height: 600 }; // Instantiate and draw our chart, passing in some options. // Do not forget to check your div ID var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <!-- this is the div that will hold the pie chart --> <div>
Error caused by short tag syntax:
Some users may encounter this error locally or on the server:
syntax error var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
This means that its environment does not support short tags. The workaround is to use the following syntax instead:
<?php echo $jsonTable; ?>
Everything should work fine.
The above is the detailed content of How to Generate Charts using PHP, MySQL, and the Google Charts API?. For more information, please follow other related articles on the PHP Chinese website!