PHPによるデータベース操作の実装

データベース連携Webアプリケーションの構築

この実装では、ユーザー情報を管理するWebアプリケーションをPHPとMySQLで構築します。データベーステーブルは名前、性別、年齢、住所、趣味の5つのフィールドで構成されています。

ログイン画面の実装

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>ユーザー認証</title>
</head>
<body>
<div style="text-align: center;">
    <h3 style="color: #32CD32; font-size: 24px;">ユーザーログイン</h3>
    <form method="post" action="process.php?operation=authenticate">
        | 氏名: | <input name="username" required="" type="text"></input> |
|---|---|
| 性別: | <input checked="checked" name="gender" type="radio" value="男性"></input>男性 <input name="gender" type="radio" value="女性"></input>女性 |
| <input type="submit" value="認証"></input> <input onclick="this.form.reset()" type="button" value="クリア"></input> |
    </form>
</div>
</body>
</html>

新規登録画面

<!DOCTYPE html>
<html>
<head>
    <title>新規登録</title>
</head>
<body>
<center>
    <h2 style="color: #FF6347;">
        <?php 
        session_start();
        echo $_SESSION['user_greeting'] . "、申し訳ございません。該当する情報が見つかりませんでした。詳細情報をご入力ください。";
        ?>
    </h2>
    <hr style="border-color: red;">
    <form method="post" action="process.php?operation=register">
        | 個人情報登録 |
|---|
| 氏名 | <input name="fullname" required="" type="text"></input> |
| 性別 | <input name="user_gender" type="radio" value="男性"></input>男性 <input name="user_gender" type="radio" value="女性"></input>女性 |
| 年齢 | <input name="user_age[]" type="checkbox" value="17"></input>17歳 <input name="user_age[]" type="checkbox" value="18"></input>18歳 <input name="user_age[]" type="checkbox" value="19"></input>19歳 <input name="user_age[]" type="checkbox" value="20"></input>20歳 |
| 居住地 | <select name="residence"> <option value="">居住地域を選択</option> <option value="東京">東京</option> <option value="大阪">大阪</option> <option value="名古屋">名古屋</option> </select> |
| 趣味・特技 | <textarea cols="28" name="interests" rows="4"></textarea> |
| <input type="submit" value="登録"></input> | <input type="reset" value="リセット"></input> |
    </form>
</center>
</body>
</html>

ユーザー情報表示画面

<?php
session_start();
try {
    $db_connection = new PDO("mysql:host=localhost;dbname=user_management", "admin", "password123");
    $db_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db_connection->exec("SET NAMES 'utf8mb4'");
} catch (PDOException $connection_error) {
    exit("データベース接続エラー: " . $connection_error->getMessage());
}

$search_query = "SELECT * FROM user_data WHERE username = ?";
$prepared_statement = $db_connection->prepare($search_query);
$prepared_statement->execute([$_SESSION['current_user']]);
$user_record = $prepared_statement->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>ユーザー情報</title>
</head>
<body>
<h2 style="color: #4169E1; text-align: center;">登録情報</h2>
<hr style="border-color: red;">
<div style="text-align: center;">
    <h3 style="font-size: 22px;">ユーザー基本情報</h3>
    | 氏名: | <input readonly="readonly" type="text" value="<?= htmlspecialchars($user_record['username']) ?>"></input> |
|---|---|
| 性別: | <input readonly="readonly" type="text" value="<?= htmlspecialchars($user_record['gender']) ?>"></input> |
| 年齢: | <input readonly="readonly" type="text" value="<?= htmlspecialchars($user_record['age']) ?>"></input> |
| 住所: | <input readonly="readonly" type="text" value="<?= htmlspecialchars($user_record['address']) ?>"></input> |
| 趣味: | <input readonly="readonly" type="text" value="<?= htmlspecialchars($user_record['hobby']) ?>"></input> |
| ['&gt;編集](<edit.php?record_id=<?= $user_record[>) ['&gt;削除](<process.php?operation=remove&record_id=<?= $user_record[>) |
    <br>
    <a href="login.php">トップページへ戻る</a>
</div>
</body>
</html>

情報編集画面

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>情報更新</title>
</head>
<body>
<hr style="border-color: red;">
<div style="text-align: center;">
    <h3 style="font-size: 22px;">情報修正</h3>
    <form method="post" action="process.php?operation=update&record_id=<?= $_GET['record_id'] ?>">
        | 氏名: | <input name="updated_name" required="" type="text"></input> |
|---|---|
| 性別: | <input name="updated_gender" type="text"></input> |
| 年齢: | <input name="updated_age[]" type="checkbox" value="17"></input>17歳 <input name="updated_age[]" type="checkbox" value="18"></input>18歳 <input name="updated_age[]" type="checkbox" value="19"></input>19歳 <input name="updated_age[]" type="checkbox" value="20"></input>20歳 |
| 住所: | <input name="updated_address" type="text"></input> |
| 趣味: | <input name="updated_hobby" type="text"></input> |
| <input type="submit" value="更新"></input> |
    </form>
</div>
</body>
</html>

処理ロジック実装

<?php
session_start();

try {
    $database = new PDO("mysql:host=localhost;dbname=user_management", "admin", "password123");
    $database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $database->exec("SET NAMES 'utf8mb4'");
} catch (PDOException $error) {
    exit("データベース接続に失敗: " . $error->getMessage());
}

switch ($_GET['operation']) {
    case 'authenticate':
        $input_name = trim($_POST['username']);
        $input_gender = $_POST['gender'];
        
        $greeting = $input_gender === '女性' ? $input_name . ' 様' : $input_name . ' 様';
        $_SESSION['user_greeting'] = $greeting;
        $_SESSION['current_user'] = $input_name;
        
        $verification_sql = "SELECT id FROM user_data WHERE username = ?";
        $stmt = $database->prepare($verification_sql);
        $stmt->execute([$input_name]);
        
        if ($stmt->rowCount() > 0) {
            $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
            $_SESSION['user_id'] = $user_data['id'];
            header("Location: profile.php");
        } else {
            header("Location: registration.php");
        }
        exit;
        
    case 'register':
        $new_name = $_POST['fullname'];
        $new_gender = $_POST['user_gender'];
        $new_hobby = $_POST['interests'] ?? '';
        $new_address = $_POST['residence'] ?? '';
        $new_age = is_array($_POST['user_age']) ? implode(',', $_POST['user_age']) : '';
        
        $_SESSION['current_user'] = $new_name;
        
        $insert_sql = "INSERT INTO user_data (gender, username, age, address, hobby) VALUES (?, ?, ?, ?, ?)";
        $insert_stmt = $database->prepare($insert_sql);
        
        if ($insert_stmt->execute([$new_gender, $new_name, $new_age, $new_address, $new_hobby])) {
            echo "<script>
                alert('登録が完了しました');
                window.location.href = 'profile.php';
            </script>";
        } else {
            echo "<script>
                alert('登録に失敗しました');
                window.history.back();
            </script>";
        }
        break;
        
    case 'remove':
        $target_id = $_GET['record_id'];
        $delete_sql = "DELETE FROM user_data WHERE id = ?";
        $delete_stmt = $database->prepare($delete_sql);
        
        if ($delete_stmt->execute([$target_id])) {
            echo "<script>
                alert('データを削除しました');
                window.location.href = 'registration.php';
            </script>";
        } else {
            echo "<script>
                alert('削除に失敗しました');
                window.history.back();
            </script>";
        }
        break;
        
    case 'update':
        $edit_id = $_GET['record_id'];
        $edit_name = $_POST['updated_name'];
        $edit_gender = $_POST['updated_gender'];
        $edit_hobby = $_POST['updated_hobby'] ?? '';
        $edit_address = $_POST['updated_address'] ?? '';
        $edit_age = is_array($_POST['updated_age']) ? implode(',', $_POST['updated_age']) : '';
        
        $update_sql = "UPDATE user_data SET username=?, gender=?, age=?, address=?, hobby=? WHERE id=?";
        $update_stmt = $database->prepare($update_sql);
        
        if ($update_stmt->execute([$edit_name, $edit_gender, $edit_age, $edit_address, $edit_hobby, $edit_id])) {
            echo "<script>
                alert('更新しました');
                window.location.href = 'profile.php';
            </script>";
        } else {
            echo "<script>
                alert('更新に失敗しました');
                window.history.back();
            </script>";
        }
        break;
}
?>

タグ: PHP MySQL pdo データベース操作 Webアプリケーション

7月18日 01:18 投稿