【问题标题】:PHP MySQL Google Chart JSON - Complete Example [closed]PHP MySQL Google Chart JSON - 完整示例 [关闭]
【发布时间】:2012-10-11 06:00:46
【问题描述】:

我进行了很多搜索,以找到一个使用 MySQL 表数据作为数据源生成 Google 图表的好示例。我搜索了几天,发现很少有示例可用于使用 PHP 和 MySQL 的组合生成 Google 图表(饼图、条形图、列图、表格)。我终于设法让一个示例正常工作。

我之前从StackOverflow那里得到了很多帮助,所以这次我会回报一些。

我有两个例子;一个使用 Ajax,另一个不使用。今天只展示非Ajax的例子。

用法:

要求:PHP、Apache 和 MySQL 安装: --- 使用 phpMyAdmin 创建数据库并将其命名为“chart” --- 使用 phpMyAdmin 创建一个表并将其命名为“googlechart”并制作 确保表只有两列,因为我使用了两列。然而, 如果您愿意,您可以使用超过 2 列,但您必须更改 为此编写一点代码 --- 指定列名如下:“weekly_task”和“percentage” --- 向表中插入一些数据 --- 对于百分比列,仅使用数字 --------------------------------- 示例数据:表格(googlechart) --------------------------------- 每周任务百分比 ------------ ---------- 睡眠 30 看电影 10 工作 40 练习 20


PHP-MySQL-JSON-Google 图表示例:

    <?php
$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 id="chart_div"></div>
  </body>
</html>


PHP-PDO-JSON-MySQL-Google 图表示例:

<?php
    /*
    Script  : PHP-PDO-JSON-mysql-googlechart
    Author  : Enam Hossain
    version : 1.0

    */

    /*
    --------------------------------------------------------------------
    Usage:
    --------------------------------------------------------------------

    Requirements: PHP, Apache and MySQL

    Installation:

      --- Create a database by using phpMyAdmin and name it "chart"
      --- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
      --- Specify column names as follows: "weekly_task" and "percentage"
      --- Insert some data into the table
      --- For the percentage column only use a number

          ---------------------------------
          example data: Table (googlechart)
          ---------------------------------

          weekly_task     percentage
          -----------     ----------

          Sleep           30
          Watching Movie  10
          job             40
          Exercise        20     


    */

    /* Your Database Name */
    $dbname = 'chart';

    /* Your Database User Name and Passowrd */
    $username = 'root';
    $password = '123456';

    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();
    }

    ?>


    <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 id="chart_div"></div>
      </body>
    </html>


PHP-MySQLi-JSON-Google 图表示例

<?php
/*
Script  : PHP-JSON-MySQLi-GoogleChart
Author  : Enam Hossain
version : 1.0

*/

/*
--------------------------------------------------------------------
Usage:
--------------------------------------------------------------------

Requirements: PHP, Apache and MySQL

Installation:

  --- Create a database by using phpMyAdmin and name it "chart"
  --- Create a table by using phpMyAdmin and name it "googlechart" and make sure table has only two columns as I have used two columns. However, you can use more than 2 columns if you like but you have to change the code a little bit for that
  --- Specify column names as follows: "weekly_task" and "percentage"
  --- Insert some data into the table
  --- For the percentage column only use a number

      ---------------------------------
      example data: Table (googlechart)
      ---------------------------------

      weekly_task     percentage
      -----------     ----------

      Sleep           30
      Watching Movie  10
      job             40
      Exercise        20     


*/

/* Your Database Name */

$DB_NAME = 'chart';

/* Database Host */
$DB_HOST = 'localhost';

/* Your Database User Name and Passowrd */
$DB_USER = 'root';
$DB_PASS = '123456';





  /* 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;


?>


<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 id="chart_div"></div>
  </body>
</html>

【问题讨论】:

标签: php mysql json charts google-visualization


【解决方案1】:

有些人可能会在本地或服务器上遇到此错误:

syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);

这意味着他们的环境不支持短标签,解决方案是使用它来代替:

<?php echo $jsonTable; ?>

一切都应该正常!

【讨论】:

    【解决方案2】:

    您可以更轻松地做到这一点。 100% 满足您的需求

    <?php
        $servername = "localhost";
        $username = "root";
        $password = "";  //your database password
        $dbname = "demo";  //your database name
    
        $con = new mysqli($servername, $username, $password, $dbname);
    
        if ($con->connect_error) {
            die("Connection failed: " . $con->connect_error);
        }
        else
        {
            //echo ("Connect Successfully");
        }
        $query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
        $aresult = $con->query($query);
    
    ?>
    
    <!DOCTYPE html>
    <html>
    <head>
        <title>Massive Electronics</title>
        <script type="text/javascript" src="loder.js"></script>
        <script type="text/javascript">
            google.charts.load('current', {'packages':['corechart']});
    
            google.charts.setOnLoadCallback(drawChart);
            function drawChart(){
                var data = new google.visualization.DataTable();
                var data = google.visualization.arrayToDataTable([
                    ['Date_time','Tempout'],
                    <?php
                        while($row = mysqli_fetch_assoc($aresult)){
                            echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
                        }
                    ?>
                   ]);
    
                var options = {
                    title: 'Date_time Vs Room Out Temp',
                    curveType: 'function',
                    legend: { position: 'bottom' }
                };
    
                var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
                chart.draw(data, options);
            }
    
        </script>
    </head>
    <body>
         <div id="areachart" style="width: 900px; height: 400px"></div>
    </body>
    </html>
    

    loder.js 链接在这里loder.js

    【讨论】:

    • 这是完整的代码吗?什么是 loder.js?我无法让它工作。
    • 它 100% 适合我。你的问题在哪里?数据从数据库中收集并创建数据图表。
    • 我用您的代码创建了一个 php 文件,建立了数据库连接,并更改了表字段名称等。它显示空白页面。我没有 loder.js。我在哪里可以买到?这可能是问题所在。
    • 非常感谢!现在可以了。你能告诉我如何定制桌子吗?我在哪里可以得到这方面的信息?因为我的数据范围很长,所以图表非常小且密集。
    • 关注此链接developers.google.com/chart/interactive/docs/quick_start 可能对您有所帮助。如果您自定义表格,只需编辑 $query = "SELECT Date_time, Tempout FROM alarm_value"; // select column 这个
    【解决方案3】:

    使用它,它确实有效:

    data.addColumn 没有你的key,你可以添加更多的列或者删除

    <?php
    $con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
    mysql_select_db("Database Name", $con); 
    // The Chart table contain two fields: Weekly_task and percentage
    //this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
    $sth = mysql_query("SELECT * FROM chart");
    
    while($r = mysql_fetch_assoc($sth)) {
    $arr2=array_keys($r);
    $arr1=array_values($r);
    
    }
    
    for($i=0;$i<count($arr1);$i++)
    {
        $chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
    }
    echo "<pre>";
    $data=json_encode($chart_array);
    ?>
    
    <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();
            data.addColumn("string", "YEAR");
            data.addColumn("number", "NO of record");
    
            data.addRows(<?php $data ?>);
    
            ]); 
          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 ur div ID
          var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
          chart.draw(data, options);
        }
        </script>
      </head>
    
      <body>
        <!--Div that will hold the pie chart-->
        <div id="chart_div"></div>
      </body>
    </html>
    

    【讨论】:

    【解决方案4】:

    有些人可能会遇到这个错误(我在实现PHP-MySQLi-JSON-Google Chart示例时遇到了它):

    您使用错误类型的数据而不是 DataTable 或 DataView 调用了 draw() 方法。

    解决方案是: 替换 jsapi 并使用 loader.js :

    google.charts.load('current', {packages: ['corechart']}) and 
    google.charts.setOnLoadCallback 
    

    --根据发行说明 --> 通过 jsapi 加载器仍然可用的 Google Charts 版本不再持续更新。请从现在开始使用新的 gstatic 加载器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-16
      • 2012-04-30
      • 2018-03-04
      • 2010-10-15
      • 1970-01-01
      • 2012-12-27
      • 2016-05-19
      • 2011-05-03
      相关资源
      最近更新 更多