PHP MySQL Google Chart JSON - 完整的範例
此範例向你展示如何使用 PHP、MySQL 和 Google Chart API 產生圖表。
先決條件:
資料庫設定:
向表中插入一些數據,其中 percentage 欄位僅包含數字。
$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>PHP-MySQL-JSON-Google Chart範例:
簡短標籤語法引起的錯誤:
syntax error var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
某些使用者可能會在本地或伺服器上遇到此錯誤:
<?php echo $jsonTable; ?>
這表示其環境不支援短標籤。解決方法是改用以下語法:
一切應該都可以正常運作了。以上是如何使用 PHP、MySQL 和 Google Charts API 產生圖表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!