首頁 > 資料庫 > mysql教程 > 如何使用 PHP、MySQL 和 JSON 建立 Google 圖表?

如何使用 PHP、MySQL 和 JSON 建立 Google 圖表?

Barbara Streisand
發布: 2024-12-08 04:40:10
原創
265 人瀏覽過

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中文網其他相關文章!

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