PHP MySQL Google Chart JSON: A Comprehensive Example
This guide provides a comprehensive example on how to generate a Google Chart using data from a MySQL table. We'll demonstrate the integration of PHP, MySQL, and the Google Chart API to create a visual representation of the data.
Requirements:
Installation:
PHP-MySQL-JSON-Google Chart Example:
<?php // Connect to the MySQL database $con = mysql_connect("localhost", "Username", "Password") or die("Failed to connect with database!!!!"); mysql_select_db("Database Name", $con); // Query the database for weekly tasks and percentages $sth = mysql_query("SELECT * FROM chart"); // Prepare the data for the Google Chart $table['cols'] = array( array('label' => 'Weekly Task', 'type' => 'string'), array('label' => 'Percentage', 'type' => 'number') ); $rows = array(); while ($r = mysql_fetch_assoc($sth)) { $temp = array(); $temp[] = array('v' => (string)$r['Weekly_task']); $temp[] = array('v' => (int)$r['percentage']); $rows[] = array('c' => $temp); } $table['rows'] = $rows; $jsonTable = json_encode($table); // Load the Google Chart API and create a pie chart ?> <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('visualization', '1', {'packages':['corechart']}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?=$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>
Error Handling:
If you encounter a "syntax error" related to short tags, use the following instead:
<?php echo $jsonTable; ?>
This ensures that PHP tags are properly closed and interpreted by your environment.
The above is the detailed content of How to Create a Google Chart from MySQL Data using PHP and JSON?. For more information, please follow other related articles on the PHP Chinese website!