PHP MySQL Google Chart JSON - 完整的示例
此示例向你展示如何使用 PHP、MySQL 和 Google Chart API 生成图表。
先决条件:
数据库设置:
PHP-MySQL-JSON-Google Chart 示例:
$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>
简短标签语法引起的错误:
一些用户可能会在本地或服务器上遇到此错误:
syntax error var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
这意味着其环境不支持短标签。解决方法是改用以下语法:
<?php echo $jsonTable; ?>
一切应该都可以正常工作了。
以上是如何使用 PHP、MySQL 和 Google Charts API 生成图表?的详细内容。更多信息请关注PHP中文网其他相关文章!