MySQLデータを可視化!PHP、MySQL、JSONでGoogleチャートを作成する方法
PHP、MySQL、JSON を用いた Google チャート作成の完全な例:詳細解説
このチュートリアルでは、PHP、MySQL、JSON を使って Google チャートを作成する例を紹介します。MySQL データベースからデータを取得し、それを JSON 形式に変換して、Google チャートで表示します。
ステップ
- MySQL データベース接続 まず、MySQL データベースに接続します。
<?php
$dbHost = "localhost";
$dbUsername = "username";
$dbPassword = "password";
$dbName = "database_name";
$connection = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);
if (!$connection) {
die("データベース接続に失敗しました:" . mysqli_connect_error());
}
?>
- MySQL データベースからデータ取得 次に、MySQL データベースから必要なデータを取得します。
$sql = "SELECT * FROM your_table";
$result = mysqli_query($connection, $sql);
if (!$result) {
die("データ取得に失敗しました:" . mysqli_error($connection));
}
- JSON 形式へのデータ変換 取得したデータを JSON 形式に変換します。
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
$jsonData = json_encode($data);
- Google チャートの作成 JSON 形式のデータを元に、Google チャートを作成します。
<!DOCTYPE html>
<html>
<head>
<title>Google チャート</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = JSON.parse('<?php echo $jsonData; ?>');
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'あなたのグラフのタイトル',
width: 600,
height: 400
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
説明
- MySQL データベース接続 この部分では、データベース接続に必要な情報 (ホスト名、ユーザー名、パスワード、データベース名) を設定します。
- MySQL データベースからデータ取得 SQL クエリを使って、必要なデータを取得します。クエリは、データを取得するテーブルと列を指定します。
- JSON 形式へのデータ変換
取得したデータを
mysqli_fetch_assoc()
関数を使って連想配列に変換し、json_encode()
関数を使って JSON 形式に変換します。 - Google チャートの作成 HTML ファイルに Google チャートのライブラリをロードし、JSON 形式のデータを解析してデータテーブルを作成します。その後、オプションを設定して、チャートの種類 (折れ線グラフなど) と表示サイズを指定し、チャートを描画します。
補足
- この例では、MySQL データベースからデータを取得していますが、他のデータソース (CSV ファイルなど) からデータを取得することも可能です。
- Google チャートにはさまざまな種類があるので、ニーズに合わせて種類を変更できます。
- チャートのオプションをカスタマイズして、外観や機能を調整できます。
関連用語
- PHP: サーバサイドスクリプティング言語
- MySQL: リレーショナルデータベース管理システム
- JSON: JavaScript Object Notation
- Google チャート: Web ブラウザ上でグラフやチャートを作成できるサービス
index.php
<?php
$dbHost = "localhost";
$dbUsername = "username";
$dbPassword = "password";
$dbName = "database_name";
$connection = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);
if (!$connection) {
die("データベース接続に失敗しました:" . mysqli_connect_error());
}
$sql = "SELECT * FROM your_table";
$result = mysqli_query($connection, $sql);
if (!$result) {
die("データ取得に失敗しました:" . mysqli_error($connection));
}
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
$jsonData = json_encode($data);
mysqli_close($connection);
?>
<!DOCTYPE html>
<html>
<head>
<title>Google チャート</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = JSON.parse('<?php echo $jsonData; ?>');
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'あなたのグラフのタイトル',
width: 600,
height: 400
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
Explanation:
- This file connects to the MySQL database, retrieves data from the
your_table
table, converts the data to JSON format, and then embeds the JSON data into the HTML document.
HTML
- This HTML code loads the Google Charts library, defines a function to draw the chart, and creates a
div
element with the IDchart_div
where the chart will be rendered.
JavaScript
- This JavaScript code parses the JSON data from the PHP code, creates a Google Visualization DataTable object from the JSON data, sets chart options, and creates a line chart using the
google.visualization.LineChart
class.
To run this example:
- Create a MySQL database named
database_name
and create a table namedyour_table
with the desired columns. - Populate the
your_table
table with data. - Save the
index.php
file to your web server. - Open
index.php
in your web browser.
You should see a line chart with the data from your your_table
table.
Additional notes:
- You can change the chart type to any other Google Chart type, such as a bar chart or a pie chart.
- You can customize the chart options to change the title, colors, and other visual elements.
- You can use more complex SQL queries to retrieve data from your MySQL database.
I hope this helps!
Using a PHP library
Using a third-party service
If you are comfortable with JavaScript, you can also create Google charts using a JavaScript library. One popular library is Google Charts JavaScript API. This library allows you to create charts directly in your JavaScript code.
Which method should you use?
The best method for you will depend on your specific needs and preferences. If you are new to Google charts, I recommend using a PHP library or a third-party service. These methods will make it easier to get started and will save you time and effort. If you are more comfortable with JavaScript, you can use the JavaScript library.
Here is an example of how to create a Google chart using the Google Charts PHP Wrapper:
<?php
require_once 'google-charts-php-wrapper/GoogleCharts.php';
$dbHost = "localhost";
$dbUsername = "username";
$dbPassword = "password";
$dbName = "database_name";
$connection = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);
if (!$connection) {
die("データベース接続に失敗しました:" . mysqli_connect_error());
}
$sql = "SELECT * FROM your_table";
$result = mysqli_query($connection, $sql);
if (!$result) {
die("データ取得に失敗しました:" . mysqli_error($connection));
}
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
mysqli_close($connection);
$gcharts = new GoogleCharts();
$chart = $gcharts->newChart('LineChart', 'Your Chart Title', ['width' => 600, 'height' => 400]);
$chart->addData($data);
echo $chart->toHtml();
?>
- This code includes the Google Charts PHP Wrapper library.
- It connects to the MySQL database, retrieves data from the
your_table
table, and converts the data to an array. - It creates a new Google Charts object and sets the chart type, title, and dimensions.
- It adds the data to the chart.
- It prints the HTML code for the chart.
php mysql json