こんにちは!今回は、DB2データベースのdb2_fetch_object
関数について、実践的に解説していきます。この関数を使うと、クエリ結果を標準オブジェクトとして取得できます。
db2_fetch_objectとは?🎯
DB2のクエリ結果を1行ずつ取得し、その行データをオブジェクトとして返す関数です。カラム名がオブジェクトのプロパティとして使用できます。
基本的な使い方
$obj = db2_fetch_object($statement);
基本的な使用例
例1:シンプルなデータ取得
$sql = "SELECT emp_id, name, department FROM employees";
$stmt = db2_exec($connection, $sql);
while ($emp = db2_fetch_object($stmt)) {
echo "社員ID: " . $emp->EMP_ID . "\n";
echo "名前: " . $emp->NAME . "\n";
echo "部署: " . $emp->DEPARTMENT . "\n";
echo "---------------\n";
}
実践的な使用例
例1:従業員クラスと組み合わせる
class Employee {
private $id;
private $name;
private $department;
private $salary;
public function __construct($data = null) {
if ($data) {
$this->id = $data->EMP_ID;
$this->name = $data->NAME;
$this->department = $data->DEPARTMENT;
$this->salary = $data->SALARY;
}
}
public function getFormattedSalary() {
return number_format($this->salary) . '円';
}
public function getDisplayName() {
return "{$this->name}({$this->department})";
}
}
function getEmployees($connection) {
$sql = "SELECT * FROM employees";
$stmt = db2_exec($connection, $sql);
$employees = [];
while ($obj = db2_fetch_object($stmt)) {
$employees[] = new Employee($obj);
}
return $employees;
}
例2:部署管理システム
class Department {
private $employees = [];
private $name;
private $totalSalary = 0;
public function __construct($name) {
$this->name = $name;
}
public function addEmployee($emp) {
$this->employees[] = $emp;
$this->totalSalary += $emp->SALARY;
}
public function getStats() {
return [
'name' => $this->name,
'count' => count($this->employees),
'totalSalary' => $this->totalSalary,
'avgSalary' => $this->totalSalary / count($this->employees)
];
}
}
function getDepartmentStats($connection) {
$sql = "SELECT * FROM employees ORDER BY department";
$stmt = db2_exec($connection, $sql);
$departments = [];
while ($emp = db2_fetch_object($stmt)) {
if (!isset($departments[$emp->DEPARTMENT])) {
$departments[$emp->DEPARTMENT] = new Department($emp->DEPARTMENT);
}
$departments[$emp->DEPARTMENT]->addEmployee($emp);
}
return $departments;
}
例3:JSONレスポンス生成
function getEmployeesJSON($connection) {
$sql = "SELECT * FROM employees";
$stmt = db2_exec($connection, $sql);
$employees = [];
while ($emp = db2_fetch_object($stmt)) {
$employeeData = [
'id' => $emp->EMP_ID,
'name' => $emp->NAME,
'department' => $emp->DEPARTMENT,
'salary' => (float)$emp->SALARY,
'fullInfo' => sprintf(
'%s(%s部署)',
$emp->NAME,
$emp->DEPARTMENT
)
];
$employees[] = $employeeData;
}
return json_encode($employees);
}
エラーハンドリング
function fetchEmployeeData($connection, $empId) {
try {
$sql = "SELECT * FROM employees WHERE emp_id = ?";
$stmt = db2_prepare($connection, $sql);
if (!$stmt) {
throw new Exception("準備されたステートメントの作成に失敗");
}
db2_bind_param($stmt, 1, $empId, DB2_PARAM_IN);
if (!db2_execute($stmt)) {
throw new Exception("クエリの実行に失敗");
}
$emp = db2_fetch_object($stmt);
if (!$emp) {
throw new Exception("従業員が見つかりません");
}
return $emp;
} catch (Exception $e) {
error_log("Error: " . $e->getMessage());
return null;
}
}
実装のTips 💡
1. カスタムクラスでの活用
class EmployeeRecord {
public function __get($name) {
// プロパティが存在しない場合の処理
return null;
}
public function getFullName() {
return $this->LAST_NAME . ' ' . $this->FIRST_NAME;
}
}
function getCustomEmployees($connection) {
$stmt = db2_exec($connection, "SELECT * FROM employees");
$employees = [];
while ($emp = db2_fetch_object($stmt, 'EmployeeRecord')) {
$employees[] = $emp;
}
return $employees;
}
2. メモリ効率の良い処理
function processLargeDataset($connection) {
$stmt = db2_exec($connection, "SELECT * FROM large_table");
while ($obj = db2_fetch_object($stmt)) {
processObject($obj);
unset($obj); // メモリ解放
}
}
3. データ検証
function validateEmployee($emp) {
return (
isset($emp->EMP_ID) &&
!empty($emp->NAME) &&
is_numeric($emp->SALARY) &&
$emp->SALARY > 0
);
}
まとめ
db2_fetch_object
はオブジェクト指向なデータアクセスが可能- クラスと組み合わせることで柔軟な処理が実現可能
- プロパティアクセスが直感的
- 大規模データ処理時はメモリ管理に注意
これでdb2_fetch_object
の使い方をマスターできましたね!
オブジェクト指向プログラミングの利点を活かした実装を行っていきましょう。
Happy Coding! 😊