Home >Database >Mysql Tutorial >How Can I Generate a Google Chart from MySQL Data Using PHP and JSON?
PHP-MySQL Google Chart JSON: A Complete Guide
Problem:
Generating a Google Chart using MySQL table data as the data source can be challenging, especially when working with PHP.
Solution:
Here's a comprehensive example that demonstrates how to use PHP, MySQL, and JSON to create a pie chart from data stored in a MySQL table.
Usage:
Install:
PHP-MySQL-JSON-Google Chart Example:
<?php // Connect to MySQL $con = mysql_connect("localhost", "Username", "Password") or die("Failed to connect!"); mysql_select_db("Database Name", $con); // Query the "googlechart" table $sth = mysql_query("SELECT * FROM googlechart"); // Create a JSON table for Google Chart $table = array( 'cols' => array( array('label' => 'Weekly Task', 'type' => 'string'), array('label' => 'Percentage', 'type' => 'number') ), 'rows' => array() ); // Populate the JSON table with data while ($r = mysql_fetch_assoc($sth)) { $rows[] = array('c' => array( array('v' => (string) $r['Weekly_task']), array('v' => (int) $r['percentage']) )); } $table['rows'] = $rows; $jsonTable = json_encode($table); // Include necessary scripts and draw the chart ?> <html> <head> <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(<?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>
Note: For other types of charts (e.g., bar charts), minor modifications to the code may be necessary.
PHP-PDO-JSON-MySQL-Google Chart Example (Alternative):
Utilizes the PHP Data Objects (PDO) extension for improved exception handling and flexibility.
PHP-MySQLi-JSON-Google Chart Example (Alternative):
Leverages the MySQLi extension for additional functionality, such as prepared statements.
Short Tag Syntax Error:
If you encounter a syntax error related to short tags (e.g., "="), ensure that they are enabled in your PHP environment or use the alternative syntax: "".
The above is the detailed content of How Can I Generate a Google Chart from MySQL Data Using PHP and JSON?. For more information, please follow other related articles on the PHP Chinese website!