首页  >  文章  >  后端开发  >  如何使用 PHP 从 MySQL 数据创建 Google 图表?

如何使用 PHP 从 MySQL 数据创建 Google 图表?

Barbara Streisand
Barbara Streisand原创
2024-11-21 10:00:13121浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn