MySQL 테이블 데이터를 데이터 소스로 사용하여 Google 차트를 생성하는 좋은 예를 찾기 위해 많은 것을 검색했습니다. 나는 며칠 동안 검색했으며 PHP와 MySQL의 조합을 사용하여 Google 차트 (파이, 바, 열, 테이블)를 생성하는 데 사용할 수있는 예제가 거의 없음을 깨달았습니다. 마침내 하나의 예제가 작동했습니다.
이전에 StackOverflow로부터 많은 도움을 받았으므로 이번에는 일부를 반환합니다.
두 가지 예가 있습니다. 하나는 Ajax를 사용하고 다른 하나는 사용하지 않습니다. 오늘은 비 Ajax 예제 만 보여줄 것이다.
용법:
요구 사항 : PHP, Apache 및 MySQL 설치: --- phpMyAdmin을 사용하여 데이터베이스를 작성하고 이름을 "chart"로 지정하십시오. --- phpMyAdmin을 사용하여 테이블을 생성하고 이름을 "googlechart"로 만들고 두 개의 열을 사용 했으므로 테이블에는 두 개의 열만 있습니다. 하나, 원하는 경우 2 개 이상의 열을 사용할 수 있지만 그것에 대해 조금 코딩 --- 다음과 같이 열 이름을 지정하십시오 : "weekly_task"및 "percentage" --- 일부 데이터를 테이블에 삽입 --- 백분율 열의 경우 숫자 만 사용하십시오. --------------------------------- 예시 데이터 : 테이블 (googlechart) --------------------------------- weekly_task 비율 ----------- ---------- 수면 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>
mysql_*
새 코드 에서는 함수를 사용하지 마십시오 . 더 이상 유지 관리되지 않으며 공식적으로 더 이상 사용되지 않습니다 . 참고 항목 빨간색 상자 ? 에 대해 알아 준비된 문 대신 사용할 PDO 또는 MySQLi를 - 이 기사는 당신이 어떤을 결정하는 데 도움이됩니다. PDO를 선택하면 다음 은 좋은 튜토리얼 입니다.