Files
php-db-question/Ex05.php
2026-10-28 14:24:02 +09:00

67 lines
2.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* [Ex05 JOINによるSELECTクエリの実行と結果の別ファイル表示]
*
* TODO:
* 1. 新しいファイル "Ex05_query.php" を作成し、PDO を用いて MySQL データベース "employee_db" に接続してください。
* DSN は "mysql:host=localhost;dbname=employee_db;charset=utf8"、
* ユーザは "rezouser"、パスワードは各自の環境に合わせて設定してください。
*
* 2. "employees", "departments", "projects" の3テーブルを JOIN した SELECT クエリを実行し、
* 従業員名、部署名、プロジェクト名を取得してください。
*
* 3. fetchAll(PDO::FETCH_ASSOC) を用いて結果セットを連想配列形式で取得し、その結果を return する
* 関数 getJoinData() を定義してください。
*
* 4. 次に、新しいファイル "Ex05.php" を作成し、require_once で "Ex05_query.php" を読み込み、
* getJoinData() を呼び出して結果を変数(例: $joinData)に格納し、HTML で結果を表示してください。
*
* 【補足説明】
* ・PDO::FETCH_ASSOC を使用すると、各行が連想配列として取得できます。
* ・この手法では、DBからの結果を一度変数に格納し、表示用のHTML部分と分離して記述できます。
*
*/
require_once __DIR__ . '/Ex05_query.php';
$joinData = getJoinData();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JOIN Query Result</title>
<link href="../common/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>JOINによるSELECTクエリの実行 結果</h1>
<?php if (!empty($joinData)): ?>
<table class="table table-bordered">
<thead>
<tr>
<th>従業員名</th>
<th>部署名</th>
<th>プロジェクト名</th>
</tr>
</thead>
<tbody>
<?php foreach ($joinData as $row): ?>
<tr>
<td><?php echo htmlspecialchars($row['employee_name']); ?></td>
<td><?php echo htmlspecialchars($row['department_name']); ?></td>
<td><?php echo htmlspecialchars($row['project_name']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p>データがありません。</p>
<?php endif; ?>
</div>
</body>
</html>