如何使用 PHP 從 MySQL 資料建立 Google 圖表?

Barbara Streisand
發布: 2024-11-21 10:00:13
原創
143 人瀏覽過

How to Create a Google Chart from MySQL Data Using PHP?

PHP MySQL Google Chart JSON - 完整範例

此問題涉及使用 PHP 和 MySQL 的組合來產生 Google 圖表。本特定內容不涉及 Ajax 的使用範例。

用法

要求

  • PHP
  • Apache
  • MySQL

安裝

  1. 建立使用 phpMyAdmin 建立名為「chart」的資料庫。
  2. 建立一個名為「googlechart」的表,其中包含兩列:「weekly_task」和「百分比」。
  3. 將範例資料插入表中,確保「百分比」欄位僅包含數字。

程式碼範例

PHP-MySQL-JSON-Google 圖表範例

<?php
// Database connection
$con = mysql_connect("localhost", "Username", "Password");
mysql_select_db("Database Name", $con);

// Query
$sth = mysql_query("SELECT * FROM chart");

// Data preparation
$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);

// HTML
?>
<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>
登入後複製

PHP-PDO-JSON-MySQL-Google 圖表範例

<?php
// Database connection
$dbname = 'chart';
$username = 'root';
$password = '123456';

$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Query
$result = $conn->query('SELECT * FROM googlechart');

// Data preparation
$rows = array();
$table['cols'] = array(
    array('label' => 'Weekly Task', 'type' => 'string'),
    array('label' => 'Percentage', 'type' => 'number')
);

foreach ($result as $r) {
    $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);

// HTML
?>
<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>
登入後複製

PHP-MySQLi-JSON-Google圖表範例

<?php
// Database connection
$DB_NAME = 'chart';
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '123456';

$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

// Query
$result = $mysqli->query('SELECT * FROM googlechart');

// Data preparation
$rows = array();
$table['cols'] = array(
    array('label' => 'Weekly Task', 'type' => 'string'),
    array('label' => 'Percentage', 'type' => 'number')
);

foreach ($result as $r) {
    $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);

// HTML
?>
<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>
登入後複製

故障排除

如果遇到以下錯誤:
syntax error var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
登入後複製

這表示您的環境不支援短標籤。要解決此問題,請改用以下程式碼:
<?php echo $jsonTable; ?>
登入後複製

以上是如何使用 PHP 從 MySQL 資料建立 Google 圖表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板