首页 >数据库 >mysql教程 >如何使用 PHP、MySQL 和 JSON 创建 Google 图表?

如何使用 PHP、MySQL 和 JSON 创建 Google 图表?

Barbara Streisand
Barbara Streisand原创
2024-12-08 04:40:10274浏览

How can I create a Google Chart using PHP, MySQL, and JSON?

PHP MySQL Google Chart JSON - 完整示例

随着技术格局的发展,可视化数据的能力变得越来越重要。 Google Chart 是一种强大的数据可视化工具。它使开发人员能够创建各种图表,包括饼图、条形图和折线图。然而,将 Google Chart 与 MySQL 数据源集成可能会带来挑战,特别是在使用 PHP 作为编程语言时。

本文提供了使用 PHP 和 MySQL 生成 Google Charts 的全面解决方案。我们将介绍多个示例来说明不同 PHP 数据访问方法的使用:

示例 1:PHP-MySQL-JSON-Google Chart(非 Ajax)

用法:

  1. 创建一个名为 MySQL 数据库“图表”。
  2. 创建一个名为“googlechart”的表,其中包含两列:“weekly_task”和“百分比”。
  3. 将示例数据插入表中,确保“百分比”列包含仅数字

代码:

$con = mysql_connect("localhost", "Username", "Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con); 
// The Chart table contains two fields: weekly_task and percentage
// This example will display a pie chart. If you need other charts such as a Bar chart, you will need to modify the code a little to make it work with bar chart and other charts
$sth = mysql_query("SELECT * FROM chart");

/*
---------------------------
example data: Table (Chart)
--------------------------
weekly_task     percentage
Sleep           30
Watching Movie  40
work            44
*/

//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(

    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'Weekly Task', 'type' => 'string'),
    array('label' => 'Percentage', 'type' => 'number')

);

$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $temp = array();
    // The following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $r['Weekly_task']); 

    // Values of each slice
    $temp[] = array('v' => (int) $r['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(<?=$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>

示例 2:PHP-PDO-JSON-MySQL-Google Chart

本示例使用 PHP 数据对象 (PDO) 连接数据库,提供了更大的灵活性和

代码:

/*
... (code) ...
*/

try {
    /* Establish the database connection */
    $conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    /* Select all the weekly tasks from the table googlechart */
    $result = $conn->query('SELECT * FROM googlechart');

    /*
        ---------------------------
        example data: Table (googlechart)
        --------------------------
        weekly_task     percentage
        Sleep           30
        Watching Movie  10
        job             40
        Exercise        20     


    */


    $rows = array();
    $table = array();
    $table['cols'] = array(

        // Labels for your chart, these represent the column titles.
        /* 
            Note that one column is in "string" format and another one is in "number" format 
            as pie chart only required "numbers" for calculating percentage 
            and string will be used for Slice title
        */

        array('label' => 'Weekly Task', 'type' => 'string'),
        array('label' => 'Percentage', 'type' => 'number')

    );

    /* Extract the information from $result */
    foreach($result as $r) {

        $temp = array();

        // The following line will be used to slice the Pie chart

        $temp[] = array('v' => (string) $r['weekly_task']); 

        // Values of each slice

        $temp[] = array('v' => (int) $r['percentage']); 
        $rows[] = array('c' => $temp);
    }

    $table['rows'] = $rows;

    // convert data into JSON format
    $jsonTable = json_encode($table);
    //echo $jsonTable;
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

?>

示例 3:PHP-MySQLi-JSON-Google Chart

此示例利用 MySQLi(MySQL 扩展的改进版本)进行数据库交互。

/*
... (code) ...
*/

/* Establish the database connection */
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

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

/* Select all the weekly tasks from the table googlechart */
$result = $mysqli->query('SELECT * FROM googlechart');

/*
    ---------------------------
    example data: Table (googlechart)
    --------------------------
    Weekly_Task     percentage
    Sleep           30
    Watching Movie  10
    job             40
    Exercise        20     
*/


$rows = array();
$table = array();
$table['cols'] = array(

    // Labels for your chart, these represent the column titles.
    /* 
        Note that one column is in "string" format and another one is in "number" format 
        as pie chart only required "numbers" for calculating percentage 
        and string will be used for Slice title
    */

    array('label' => 'Weekly Task', 'type' => 'string'),
    array('label' => 'Percentage', 'type' => 'number')

);

/* Extract the information from $result */
foreach($result as $r) {

    $temp = array();

    // The following line will be used to slice the Pie chart

    $temp[] = array('v' => (string) $r['weekly_task']); 

    // Values of the each slice

    $temp[] = array('v' => (int) $r['percentage']); 
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;

// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;


以上是如何使用 PHP、MySQL 和 JSON 创建 Google 图表?的详细内容。更多信息请关注PHP中文网其他相关文章!

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