Saya telah mencari banyak untuk menemukan contoh yang baik untuk menghasilkan Google Chart menggunakan data tabel MySQL sebagai sumber data. Saya mencari beberapa hari dan menyadari bahwa ada beberapa contoh yang tersedia untuk menghasilkan Google Chart (pie, bar, kolom, tabel) menggunakan kombinasi PHP dan MySQL. Saya akhirnya berhasil membuat satu contoh berfungsi.
Saya sebelumnya telah menerima banyak bantuan dari StackOverflow, jadi kali ini saya akan mengembalikan beberapa.
Saya punya dua contoh; satu menggunakan Ajax dan yang lainnya tidak. Hari ini, saya hanya akan menunjukkan contoh non-Ajax.
Pemakaian:
Persyaratan: PHP, Apache dan MySQL Instalasi: --- Buat database dengan menggunakan phpMyAdmin dan beri nama "grafik" --- Buat tabel dengan menggunakan phpMyAdmin dan beri nama "googlechart" dan buat tabel yakin hanya memiliki dua kolom karena saya telah menggunakan dua kolom. Namun, Anda dapat menggunakan lebih dari 2 kolom jika suka tetapi Anda harus mengubah kode sedikit untuk itu --- Tentukan nama kolom sebagai berikut: "Weekly_task" dan "persentase" --- Masukkan beberapa data ke dalam tabel --- Untuk kolom persentase hanya menggunakan angka --------------------------------- contoh data: Tabel (googlechart) --------------------------------- persentase Weekly_task ----------- ---------- Tidur 30 Menonton Film 10 pekerjaan 40 Latihan 20
Contoh PHP-MySQL-JSON-Google Chart:
<?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>
Contoh PHP-PDO-JSON-MySQL-Google Chart:
<?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>
Contoh PHP-MySQLi-JSON-Google Chart
<?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_*
fungsi dalam kode baru . Mereka tidak lagi dipertahankan dan secara resmi ditinggalkan . Lihat kotak merah ? Pelajari tentang pernyataan yang disiapkan , dan gunakan PDO atau MySQLi - artikel ini akan membantu Anda memutuskan yang mana. Jika Anda memilih PDO, berikut adalah tutorial yang bagus .Jawaban:
Beberapa orang mungkin mengalami kesalahan ini baik secara lokal atau di server:
Ini berarti bahwa lingkungan mereka tidak mendukung tag pendek solusinya adalah dengan menggunakan ini:
Dan semuanya akan bekerja dengan baik!
sumber
Anda dapat melakukan ini dengan cara yang lebih mudah. Dan 100% berhasil yang Anda inginkan
link loder.js di sini loder.js
sumber
$query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
inigunakan ini, ini benar-benar berfungsi:
data.addColumn no dari kunci Anda, Anda dapat menambahkan lebih banyak kolom atau menghapus
sumber
Beberapa orang mungkin mengalami kesalahan ini (saya mendapatkannya saat menerapkan PHP-MySQLi-JSON-Google Chart Contoh):
Solusinya adalah: ganti jsapi dan gunakan loader.js dengan:
- sesuai dengan catatan rilis -> Versi Google Charts yang tetap tersedia melalui loader jsapi tidak lagi diperbarui secara konsisten. Silakan gunakan loader gstatic baru mulai sekarang.
sumber