복붙노트

PHP MySQL의 Google 차트 JSON - 전체 예제

PHP

PHP MySQL의 Google 차트 JSON - 전체 예제

필자는 MySQL 테이블 데이터를 데이터 소스로 사용하여 Google Chart를 생성하는 좋은 예를 찾기 위해 많은 조사를 해왔습니다. 며칠 동안 검색 한 결과, PHP와 MySQL의 조합을 사용하여 Google 차트 (파이, 막대, 열, 표)를 생성 할 수있는 몇 가지 예가 있음을 알았습니다. 마침내 한 가지 예를 다루게되었습니다.

이전에 StackOverflow에서 많은 도움을 받았으므로 이번에는 몇 가지를 반환 할 것입니다.

두 가지 예가 있습니다. 하나는 Ajax를 사용하고 다른 하나는 사용하지 않습니다. 오늘은 Ajax가 아닌 예제만을 보여 드리겠습니다.

용법:

    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    

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>

해결법

  1. ==============================

    1.일부는 로컬 또는 서버에서이 오류가 발생할 수 있습니다.

    일부는 로컬 또는 서버에서이 오류가 발생할 수 있습니다.

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

    이것은 그들의 환경이 해결책이 이것을 대신 사용하는 짧은 태그를 지원하지 않는다는 것을 의미합니다 :

    <?php echo $jsonTable; ?>
    

    모든 것이 잘 작동합니다!

  2. ==============================

    2.이것을 사용하면 실제로 작동합니다.

    이것을 사용하면 실제로 작동합니다.

    data.addColumn 키가 없습니다. 더 많은 열을 추가하거나 제거 할 수 있습니다.

    <?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>
    
  3. ==============================

    3.이 작업을보다 쉽게 ​​할 수 있습니다. 100 % 원하는대로 작동합니다.

    이 작업을보다 쉽게 ​​할 수 있습니다. 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

  4. ==============================

    4.일부는이 오류가 발생할 수 있습니다 (PHP-MySQLi-JSON-Google 차트 예제를 구현하는 동안 가져 왔습니다).

    일부는이 오류가 발생할 수 있습니다 (PHP-MySQLi-JSON-Google 차트 예제를 구현하는 동안 가져 왔습니다).

    해결책은 다음과 같습니다. jsapi를 대체하고 loader.js를 다음과 같이 사용하십시오 :

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

    - 출시 노트에 따르면 -> jsapi 로더를 통해 사용할 수있는 Google Charts의 버전은 더 이상 일관되게 업데이트되지 않습니다. 새로운 gstatic 로더를 사용하십시오.

  5. from https://stackoverflow.com/questions/12994282/php-mysql-google-chart-json-complete-example by cc-by-sa and MIT license