examsテーブルに以下のデータが入っているとする。
Table: テーブル例
| id | name | score | 
| 1 | student1 | 49 | 
| 2 | student2 | 30 | 
| 3 | student3 | 86 | 
Example: exams_table.php
<?php
/* SQLサーバに接続 */
$conn_id = mysql_connect("localhost", "ユーザ名", "パスワード") or die ('Error connecting to mysql');
/* DBを選択 */
mysql_select_db('データベース名', $conn_id);
/* examsテーブルからname, scoreを取得する */
$query = "SELECT name, score FROM exams";
$result = mysql_query($query, $conn_id) or die ($query . ' failed (' . mysql_error() . ')');
echo "<table border=1>\n";
echo "<tr><th>Name</th><th>Score</th></tr>\n";
while ($row = mysql_fetch_object($result)) {
 echo "<tr>";
 echo "<td>" . $row->name . "</td>\n";
 echo "<td>" . $row->score . "</td>\n";
 echo "</tr>\n";
}
echo "</table>\n";
mysql_free_result($result);
/* SQLサーバから切断 */
mysql_close($conn_id);
?>
グラフを作成し画像として出力する。Example: exams_graph.php
<?php
include ("jpgraph/jpgraph.php");
include ("jpgraph/jpgraph_bar.php");
$ydata = array();
$a = array();
/* SQLサーバに接続 */
$conn_id = mysql_connect("localhost", "ユーザ名", "パスワード") or die ('Error connecting to mySQL server');
/* DBを選択 */
mysql_select_db("データベース名", $conn_id);
 
/* examsテーブルから使用量を取得する */
$query = "SELECT name, score FROM exams";
$result = mysql_query($query, $conn_id) or die ($query . ' failed (' . mysql_error() . ')');
/* データを配列に格納する */
while ($row = mysql_fetch_object($result)) {
 array_push($ydata, $row->score);
 array_push($a, $row->name);
}
mysql_free_result($result);
/* SQLサーバから切断 */
mysql_close($conn_id);
/* グラフ作成 */
$graph = new Graph(350, 250, "auto");
$graph->SetScale("textlin");
/* X軸項目追加 */
$graph->xaxis->SetTickLabels($a);
/* plot作成 */
$bplot = new BarPlot($ydata);
/* グラフ上に描画 */
$graph->Add($bplot);
/* グラフ表示 */
$graph->Stroke();
?>
表とグラフを表示するページExample: exams.php
<!DOCTYPE HTML PUBLIC "-//IETF/DTD HTML//EN">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Exam</title>
</head>
<body>
<?php
  require('exams_table.php');
?>
<br><br>
<img src="exams_graph.php">
</body></html>
グラフはこのようなものが表示される。

 
0 件のコメント:
コメントを投稿